package com.ltmall.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ltmall.api.bean.*;
import com.ltmall.api.comm.HttpClientUtil;
import com.ltmall.api.comm.Path;
import com.ltmall.api.comm.SensetiveWord;
import com.ltmall.api.comm.TimeUtil;
import com.ltmall.api.entity.JsonOrder;
import com.ltmall.api.entity.JsonOrderContent;
import com.ltmall.api.entity.JsonOrderNumber;
import com.ltmall.api.entity.param.OrderParam;
import com.ltmall.api.manager.*;
import com.ltmall.api.news.NewsCenter;
import com.ltmall.api.parse.GoodsParse;
import com.ltmall.api.parse.OrderParse;
import com.ltmall.api.pay.zfb.PayUtils;
import com.ltmall.api.rule.CSG;
import com.ltmall.api.util.PageUtil;
import com.ltmall.api.util.RemoteUtil;
import com.ltmall.api.weixin.pay.Constants;
import com.ltmall.api.weixin.pay.utils.WeixinUtils;
import com.ltmall.api.weixin.pay.utils.WeixinUtils.WXPayType;
import com.ltmall.api.weixin.tecent.comm.RandomStringGenerator;
import com.ltmall.api.weixin.util.TemplateMessageUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.Map.Entry;

//import com.alipay.api.internal.util.AlipaySignature;

/*
 * 购物车控制器
 */
@Controller
public class OrderController {

    boolean opTag, valiTag;
    private OrderManager orderManager;
    private CartManager cartManager;
    private AccountManager accountManager;
    private GoodsManager goodsManager;
    private LogisticManager logiManager;
    private NewsManager newsManager;
    private WalletManager walletManager;
    private SubUnderwritingManager subUnderwritingManager;
    private DirectSupplyManager directoryManager;
    private DirectSupplyGoodsManager directSupplyGoodsManager;

    public void setDirectoryManager(DirectSupplyManager directoryManager) {
        this.directoryManager = directoryManager;
    }

    private static Logger logger = LogManager.getLogger(OrderController.class);

    public SubUnderwritingManager getSubUnderwritingManager() {
        return subUnderwritingManager;
    }

    public void setSubUnderwritingManager(SubUnderwritingManager subUnderwritingManager) {
        this.subUnderwritingManager = subUnderwritingManager;
    }

    public WalletManager getWalletManager() {
        return walletManager;
    }

    public void setWalletManager(WalletManager walletManager) {
        this.walletManager = walletManager;
    }

    public NewsManager getNewsManager() {
        return newsManager;
    }

    public void setNewsManager(NewsManager newsManager) {
        this.newsManager = newsManager;
    }

    public LogisticManager getLogiManager() {
        return logiManager;
    }

    public void setLogiManager(LogisticManager logiManager) {
        this.logiManager = logiManager;
    }

    public GoodsManager getGoodsManager() {
        return goodsManager;
    }

    public void setGoodsManager(GoodsManager goodsManager) {
        System.out.println("setGoodsManager:" + goodsManager);
        this.goodsManager = goodsManager;
    }

    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public CartManager getCartManager() {
        return cartManager;
    }

    public void setCartManager(CartManager cartManager) {
        this.cartManager = cartManager;
    }

    public OrderManager getOrderManager() {
        return orderManager;
    }

    public void setOrderManager(OrderManager orderManager) {
        this.orderManager = orderManager;
    }

    // 提醒发货
    public void deliveryRemind(HttpServletRequest request, HttpServletResponse response) {

        long oneDay = 1 * 24 * 60 * 60 * 1000l;
        String orderID = request.getParameter("orderID");
        String userID = request.getParameter("userID");
        Order order = orderManager.getOrder(Integer.parseInt(orderID));

        if (order.getStation() == 3) {// 已经发货的商品
            RemoteUtil.response(response, null, -3, "商品已经发货");
            return;
        }

        // 最近的一条消息
        ShopNews latestNews = orderManager.getShopNews(order.getShopID(), Integer.parseInt(userID));
        if (latestNews != null && (System.currentTimeMillis() - latestNews.getOpTime() < oneDay)) {
            RemoteUtil.response(response, null, -2, "今日已经提醒");
            return;
        }

        // 判断发货时间间隔
        ShopNews news = new ShopNews();
        news.setContent("买家提醒订单号为：" + orderID + "的订单发货");
        news.setFromID(Integer.parseInt(userID));
        news.setShopID(order.getShopID());
        news.setTitle("发货提醒");
        news.setIsRead(0);

        opTag = orderManager.addShopNews(news);
        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    // 订单生成
    public void orderAdd(HttpServletRequest request, HttpServletResponse response) {

        ArrayList<Integer> skuIdList = new ArrayList<Integer>();//sku
        String context = "订单创建失败";//返回信息
        List<Cart> cartList = new ArrayList<Cart>();

        OrderParam param = (OrderParam) RemoteUtil.request(request, new OrderParam());
        String cartIDArr[] = param.getCartID().split(";");// 购物车ID的数组

        //【1】身份验证
        valiTag = accountManager.validate(param.getUserID(), param.getUserToken());
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        //【2】订单合法性验证
        for (String c : cartIDArr) {

            //查询购物车详情
            Cart cart = cartManager.cartDetail(Integer.parseInt(c));
            skuIdList.add(cart.getSkuID());
            cartList.add(cart);
            //查询商品sku
            ThSku sku = goodsManager.skuGet(cart.getSkuID());
            //查询商品详情
            Goods goods = goodsManager.goodsDetail(sku.getGoodsID());

            if (cart.getGroupID() == 0 && cart.getDirectID() == 0) {
                //【2.1】普通商品合法性验证
                //【2.1.1】商品是否限购
                //防止商品数量为0
                if (cart.getNumber() <= 0) {
                    RemoteUtil.response(response, null, -6, "订单数量异常");
                    return;
                }
                int numberLimit = checkNumberLimit(cart);
                if (numberLimit != 1) {
                    switch (numberLimit) {
                        case -4:
                            context = "活动库存不足";
                            break;
                        case -5:
                            context = "超过活动限购";
                            break;
                    }
                    RemoteUtil.response(response, null, numberLimit, context);
                    return;
                }

                //【2.1.2】商品是否下架
                if (goods.getStation() == -2) {// 下架了
                    // 判断该商品是否存在今日疯抢，如果正在今日疯抢中 这个逻辑是存在问题的
                    ActivityPrice ap = orderManager.getActivityPriceBySkuID(sku.getID());
                    if (ap == null) {// 商品下架了，也不存在活动商品
                        RemoteUtil.response(response, null, -6, "商品已经下架");
                        return;
                    }
                }

                //【2.1.3】商品库存是否足够
                int cartNumber = orderManager.goodsNumberInCart(sku.getGoodsID(), cartIDArr);
                if (cartNumber > sku.getStock()) {
                    RemoteUtil.response(response, null, -3, "商品库存不足");
                    return;
                }

            } else if (cart.getGroupID() != 0) {

                //【2.2】团购商品合法性验证
                int groupRulesID = cart.getGroupRulesID();
                int num = cart.getNumber();
                ThGroupBuyingRules groupRules = goodsManager.groupBuyingRuleGet(groupRulesID);
                //【2.2.1】购买数量不能小于1
                int numberLimit = 1;
                if (num < 1) {
                    RemoteUtil.response(response, null, -2, "购买数量不支持");
                    return;
                }

                //【2.2.2】团购合法性校验
                int groupGoodsId = 0;
                if (groupRulesID > 0) {
                    numberLimit = checkJoinGroupBuying(cart.getUserID(), groupRules, num,
                            cart.getGroupID());
                    if (numberLimit != 1) {
                        switch (numberLimit) {
                            case -5:
                                context = "团购已经过期";
                                break;
                            case -7:
                                context = "超过限购数量";
                                break;
                        }
                    }
                } else {
                    numberLimit = 0;
                    context = "参数错误";
                }
                if (numberLimit != 1) {
                    RemoteUtil.response(response, groupGoodsId, numberLimit, context);
                    return;
                }
            }
        }

        //【3】添加订单
        List<JsonOrder> returnList = orderManager.ordersadd(cartList, param.getUserID(),
                param.getAddressID(), param.getSelfAddId());
        String message = returnList == null ? "创建失败" : "返回成功";
        int code = returnList == null ? -1 : 1;

        RemoteUtil.response(response, returnList, code, message);
    }

    public void ordersAdd(HttpServletRequest request, HttpServletResponse response) {
        long startTime = System.currentTimeMillis();
        OrderParam param = (OrderParam) RemoteUtil.request(request, new OrderParam());
        ArrayList<Integer> skuIdList = new ArrayList<Integer>();
        String context = null;
        int numberLimit = 1;
        //test
        /*param.setCartID("20807");
        param.setAddressID(1926);
        param.setUserID(1008590);*/

        String cartIDArr[] = param.getCartID().split(";");// 购物车ID的数组
        List<Cart> cartList = new ArrayList<Cart>();

        //【1】身份合法性验证
        /*valiTag = accountManager.validate(param.getUserID(), param.getUserToken());
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }*/

        //【2】订单合法性验证
        for (String c : cartIDArr) {
            Cart cart = cartManager.cartDetail(Integer.parseInt(c));
            skuIdList.add(cart.getSkuID());
            cartList.add(cart);
            ThSku sku = goodsManager.skuGet(cart.getSkuID());
            Goods goods = goodsManager.goodsDetail(sku.getGoodsID());
            //【2.1】商品是否限购
            if (cart.getNumber() <= 0) {
                RemoteUtil.response(response, null, -6, "订单数量异常");
                return;
            }
            if (cart.getActivityID() > 0) {
                //numberLimit = checkActivityNumberLimit(cart, cart.getNumber());//耗时长
            } else {
                numberLimit = checkNumberLimit(cart.getGoodsID(), cart.getNumber(), cart.getSkuID());//耗时长
            }
            if (numberLimit != 1) {
                switch (numberLimit) {
                    case -3:
                        context = "商品库存不足";
                        break;
                    case -4:
                        context = "活动库存不足";
                        break;
                    case -5:
                        context = "超过活动限购";
                        break;
                    case -6:
                        context = "活动已经过期";
                        break;
                    case -9:
                        context = "不支持购买";
                        break;
                }
                RemoteUtil.response(response, null, numberLimit, context);
                return;
            }

            //【2.2】商品是否下架
            if (goods.getStation() == -2) {// 下架了
                // 判断该商品是否存在今日疯抢，如果正在今日疯抢中 这个逻辑是存在问题的
                ActivityPrice ap = orderManager.getActivityPriceBySkuID(sku.getID());
                if (ap == null) {// 商品下架了，也不存在活动商品
                    RemoteUtil.response(response, null, -6, "商品已经下架");
                    return;
                }
            }

            //【2.3】商品库存是否足够
            int cartNumber = orderManager.goodsNumberInCart(sku.getGoodsID(), cartIDArr);
            if (cartNumber > sku.getStock()) {
                RemoteUtil.response(response, null, -3, "商品库存不足");
                return;
            }
        }

        System.out.println("ordersAdd1 spendTime:" + (System.currentTimeMillis() - startTime));

        //【3】添加订单
        List<JsonOrder> returnList = orderManager.ordersadd(cartList, param.getUserID(),
                param.getAddressID(), param.getSelfAddId());
        String message = returnList == null ? "创建失败" : "返回成功";
        int code = returnList == null ? -1 : 1;
        System.out.println("ordersAdd2 spendTime:" + (System.currentTimeMillis() - startTime));
        RemoteUtil.response(response, returnList, code, message);
    }

    // 判断是否可以团购
    private int checkJoinGroupBuying(int userId, ThGroupBuyingRules groupRules, int num, int groupId) {
        /*List<ThGroupBuying> list = new ArrayList<ThGroupBuying>();
        list = goodsManager.groupBuyingGroupGet(groupRules.getId(), 0);
        System.out.println("checkJoinGroupBuying:已经开团数量" + list.size());
        if (groupId == 0) { // 开团
            if (list != null && list.size() >= groupRules.getGroupLimit()) {
                return -3;
            }
        }*/

        int state = groupRules.getState();
        if (state != 1) {
            return -5;
        }

        if (num > groupRules.getGoodsLimitBuy()) {
            return -7;
        }

        return 1;
    }

    // 团购直接购买
    public void joinGroupBuying(HttpServletRequest request, HttpServletResponse response) {

        OrderParam param = (OrderParam) RemoteUtil.request(request, new OrderParam());

        //【1】身份校验
        valiTag = accountManager.validate(param.getUserID(), param.getUserToken());
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        int userID = Integer.parseInt(request.getParameter("userID"));
        int skuID = Integer.parseInt(request.getParameter("skuID"));
        int directID = Integer.parseInt(request.getParameter("directId"));
        int num = Integer.parseInt(request.getParameter("num"));
        int groupRulesID = 0;
        if (request.getParameter("groupRulesID") != null) {
            groupRulesID = Integer.parseInt(request.getParameter("groupRulesID"));
        }
        int groupID = 0;
        if (request.getParameter("groupID") != null) {
            groupID = Integer.parseInt(request.getParameter("groupID"));
        }

        logger.info("【团购下单参数】:" + "directID:" + directID);

        //【1】查询团购信息
        ThGroupBuyingRules groupRules = goodsManager.groupBuyingRuleGet(groupRulesID);
        ThSku sku = goodsManager.skuGet(skuID);

        //【2】团购业务判断
        //【2.1】购买数量不能小于1
        int numberLimit = 1;
        String context = null;
        if (num < 1) {
            context = "购买数量不支持";
            numberLimit = -2;
            RemoteUtil.response(response, null, numberLimit, context);
            return;
        }

        //【2.2】团购合法性校验
        int groupGoodsId = 0;
        if (groupRulesID > 0) {
            numberLimit = checkJoinGroupBuying(userID, groupRules, num, groupID);
            if (numberLimit != 1) {
                switch (numberLimit) {
                    case -5:
                        context = "团购已经过期";
                        break;
                    case -7:
                        context = "超过限购数量";
                        break;
                }
            }
        } else {
            numberLimit = 0;
            context = "参数错误";
        }

        if (numberLimit != 1) {
            RemoteUtil.response(response, groupGoodsId, numberLimit, context);
            return;
        }

        List<JsonOrder> returnList = new ArrayList<JsonOrder>();
        float orderFee = 0;
        JsonOrder jo = new JsonOrder();

        //【3】创建订单
        //【3.1】保存订单物流信息
        Order order = createOrderForGroup(userID, groupRules.getShopId());
        if (param.getAddressID() != 0 || param.getSelfAddId() != 0)// 有地址
            orderManager.addOrder(order);// 插入订单

        //【3.2】 保存订单时间
        OrderTime oTime = new OrderTime();
        oTime.setOrderID(order.getOrderID());
        orderManager.addOrderTime(oTime);// 插入订单时间

        //【3.3】保存订单内容
        List<OrderContent> contentList = orderContentAddForGroup(order.getOrderID(), groupRules,
                num, groupID, sku, directID);
        if (param.getAddressID() != 0 || param.getSelfAddId() != 0)// 有地址
        {
            for (OrderContent content : contentList) {
                orderManager.addOrderContent(content);// 插入内容
            }
        }

        //【3.4】保存订单发货信息，更新订单总费用（商品价格+邮费）
        OrderLogistic logistic = createOrderLogisticForGroup(order.getOrderID(),
                param.getAddressID(), param.getSelfAddId(), groupRules.getGoodsId(), num);
        if (param.getAddressID() != 0 || param.getSelfAddId() != 0)// 有地址
        {
            orderManager.addOrderLogistic(logistic);// 插入物流
            // 本次订单的总费用
            for (OrderContent content : contentList) {
                orderFee += content.getFee();
            }
            orderManager.updateOrderFee(order.getOrderID(), (orderFee + logistic.getFee()));//修改订单的价格(商品费用加上物流费用)
        }
        order = orderManager.getOrder(order.getOrderID());
        jo.setOrder(order);
        jo.setOrderContent(contentList);
        jo.setOrderLogistic(logistic);
        returnList.add(jo);
        logger.info("【团购下单返回订单信息】:" + order);

        RemoteUtil.response(response, returnList, 1, "返回成功");

    }

    // 直接购买,不经过购物车
    public void goodsBuy(HttpServletRequest request, HttpServletResponse response) {
        int userID = Integer.parseInt(request.getParameter("userID"));
        int groupRulesID = 0;
        if (request.getParameter("groupRulesID") != null) {
            groupRulesID = Integer.parseInt(request.getParameter("groupRulesID"));
        }
        int num = Integer.parseInt(request.getParameter("num"));
        OrderParam param = (OrderParam) RemoteUtil.request(request, new OrderParam());
        /*valiTag = accountManager.validate(param.getUserID(), param.getUserToken());
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }*/

        ThGroupBuyingRules groupRules = goodsManager.groupBuyingRuleGet(groupRulesID);
        int shopId = groupRules.getShopId();
        int goodsId = groupRules.getGoodsId();
        String context = null;

        int numberLimit = 1;

        if (num < 1) {
            context = "购买数量不支持";
            numberLimit = -2;
            RemoteUtil.response(response, null, numberLimit, context);
            return;
        }

        if (groupRulesID > 0) {
            numberLimit = checkNumberLimit(goodsId, num, groupRules.getSkuId());
            if (numberLimit != 1) {
                switch (numberLimit) {
                    case -3:
                        context = "库存不够了";
                        break;
                    case -6:
                        context = "商品已经下架";
                        break;
                }
            }
        } else {
            numberLimit = 0;
            context = "参数错误";
        }

        if (numberLimit != 1) {
            RemoteUtil.response(response, null, numberLimit, context);
            return;
        }

        List<JsonOrder> returnList = new ArrayList<JsonOrder>();

        float orderFee = 0;
        JsonOrder jo = new JsonOrder();
        /*
         * 1：生成订单 1.1:创建订单时间 （OrderTime） 2：生成物流 3：生成订单内容 4：修改订单总价格
         */
        Order order = createOrderForGroup(userID, shopId);

        if (param.getAddressID() != 0)// 有地址
            orderManager.addOrder(order);// 插入订单

        // 提交订单时间
        OrderTime oTime = new OrderTime();
        oTime.setOrderID(order.getOrderID());
        orderManager.addOrderTime(oTime);// 插入订单时间

        // List<OrderContent> contentList =
        // orderContentAddForGroup(order.getOrderID(),groupRules, num,groupID);
        List<OrderContent> contentList = orderBuyContentAdd(order.getOrderID(), groupRules, num);
        if (param.getAddressID() != 0)// 有地址
        {
            for (OrderContent content : contentList) {
                orderManager.addOrderContent(content);// 插入内容
            }
        }
        OrderLogistic logistic = createOrderLogisticForGroup(order.getOrderID(),
                param.getAddressID(), param.getSelfAddId(), goodsId, num);
        if (param.getAddressID() != 0)// 有地址
        {
            orderManager.addOrderLogistic(logistic);// 插入物流
            // 本次订单的总费用
            for (OrderContent content : contentList) {
                orderFee += content.getFee();
            }
            orderManager.updateOrderFee(order.getOrderID(), (orderFee + logistic.getFee()));// 修改订单的价格(商品费用加上物流费用)
        }
        jo.setOrder(order);
        jo.setOrderContent(contentList);
        jo.setOrderLogistic(logistic);
        returnList.add(jo);

        RemoteUtil.response(response, returnList, 1, "返回成功");

    }

    private int checkActivityNumberLimit(Cart list, int number) {
        /*
         * -4:活动商品库存不足； -5:超过限购数量； -6:活动不存在
         */
        List<?> oc = null;
        int orderNum = 0;

        ActivityPrice actSku = null;
        // 判断商品是否处于今日疯抢的活动中
        if (list.getActivityName().equals("ThPanicBuyingSku") && list.getActivityID() > 0) {
            // actSku =
            // cartManager.panicSKuGet(list.getSkuID(),list.getActivityID());
            actSku = orderManager.getActivityPriceBySkuID(list.getSkuID());
            if (actSku != null) {
                // 根据SkuId从订单中查找该商品
                oc = cartManager.ordersGet(list.getSkuID(), list.getUserID(), "ThPanicBuyingSku",
                        actSku.getActivityID());
                for (int i = 0; i < oc.size(); i++) {
                    orderNum += Integer.parseInt(oc.get(i).toString());
                }
            } else {
                return -6;
            }
        }

        if (orderNum + number > actSku.getLimit()) {
            return -5;
        } else if (number > actSku.getNumber()) {
            return -4;
        }
        return 1;
    }

    public int checkPanic(int id, int userId) {
        List<OrderContent> contentList = orderManager.getOrderContent(id);
        for (OrderContent content : contentList) {
            // 只管orderContent
            if (content.getActivityID() > 0 && content.getActivityName().equals("ThPanicBuyingSku")) {
                Cart cart = new Cart();
                cart.setActivityID(content.getActivityID());
                cart.setActivityName(content.getActivityName());
                cart.setGoodsID(content.getGoodsID());
                cart.setSkuID(content.getSkuID());
                cart.setGoodsFormat(content.getGoodsFormat());
                cart.setUserID(userId);

                int flag = checkActivityNumberLimit(cart, content.getGoodsNumber());

                if (flag < 1) {
                    return flag;
                }

                boolean tag = orderManager.decreasePanicStocks(content.getActivityID(),
                        content.getGoodsID(), content.getGoodsFormat(), content.getGoodsNumber());
                if (tag == false) {
                    return -10;
                }
                // 原来的商品要添加销量
                // goodsManager.updateSellOut(content.getGoodsID(),
                // content.getGoodsNumber());
            }
        }
        return 1;
    }

    // 检查普通商品购买限制
    private int checkNumberLimit(int goodsID, int buyNumber, int skuID) {
        // 检查库存是否还能够支持继续购买
        Goods goods = goodsManager.goodsDetail(goodsID);
        ThSku sku = goodsManager.skuGet(skuID);
        if (sku.getStock() < buyNumber) {// 大于商品库存
            return -3;
        }
        if (goods.getStation() != 1) {
            return -6;
        }
        if (goods.getGoodsType() == 3) {
            PrePay prePay = goodsManager.getPrepay(goodsID);
            String endTime = prePay.getEndTime() + ":00";
            Timestamp ss = Timestamp.valueOf(endTime);
            long endTimeLong = ss.getTime();
            long now = System.currentTimeMillis();
            if (now > endTimeLong) {
                return -9;
            }
        }
        return 1;
    }

    public void isPriceChanged(HttpServletRequest request, HttpServletResponse response) {
        String param = request.getParameter("goodsPrice");
        JSONArray goodsPriceArray = JSONArray.parseArray(param);
        boolean pirceSame = true;
        List<String> goodsIdList = new ArrayList<String>();
        for (Object object : goodsPriceArray) {
            JSONObject jsonObject = (JSONObject) object;
            String price = (String) jsonObject.get("goodsPrice");
            String skuId = (String) jsonObject.get("skuID");
            String goodsId = (String) jsonObject.get("goodsID");
            if (!orderManager.isPriceSame(price, skuId)) {
                pirceSame = false;
                goodsIdList.add(goodsId);
            }
        }
        if (pirceSame) {
            RemoteUtil.response(response, null, 1, "价格没有变化");
        } else {
            List<Goods> goods = new ArrayList<Goods>();
            for (String goodsId : goodsIdList) {
                goods.add(goodsManager.goodsDetail(Integer.parseInt(goodsId)));
            }
            Object object = JSON.toJSON(goods);
            RemoteUtil.response(response, object, 0, "价格发生变化");
        }
    }

    private List<OrderContent> orderContentAddForGroup(int orderID, ThGroupBuyingRules rule,
                                                       int num, int groupID, ThSku sku, int directID) {
        List<OrderContent> contentList = new ArrayList<OrderContent>();
        OrderContent content = new OrderContent();
        int goodsId = rule.getGoodsId();
        double price = 0;

        //判断是否为阶梯费用
        if (rule.getIsLadderPrice() == 0) {
            //不执行阶梯价格
            price = sku.getPrice();
        } else {
            //执行阶梯价格
            int groupJoinPeople = 0; //参团人数
            ThGroupBuying group = goodsManager.groupBuyingGetByRulesId(rule.getId());
            //首次开团
            if (group != null) {
                groupJoinPeople = group.getGroupJoinPeople();
            }

            //判断当前团购人数属于哪个区间
            if (groupJoinPeople < rule.getLevel2Num()) {
                price = Double.parseDouble(sku.getLevel1Price());
            } else if (groupJoinPeople >= rule.getLevel2Num()
                    && groupJoinPeople < rule.getLevel3Num()) {
                price = Double.parseDouble(sku.getLevel2Price());
            } else if (groupJoinPeople >= rule.getLevel3Num()) {
                price = Double.parseDouble(sku.getLevel3Price());
            }
        }

        //支付费用
        content.setFee(price * num);

        //商品价格
        content.setGoodsPrice(price);

        //保存商品名称和图片
        Goods goods = goodsManager.goodsDetail(goodsId);
        content.setGoodsTitle(goods.getGoodsTitle());
        content.setGoodsPicture(GoodsParse.getOneGoodsPicture(goods.getGoodsPicture()));

        //保存商家编号和名称
        Shop shop = goodsManager.shopDetail(rule.getShopId());
        content.setShopName(shop.getShopName());
        content.setShopID(shop.getShopID());

        content.setDirectID(directID);

        content.setGoodsID(goodsId);
        content.setGoodsNumber(num);
        content.setGoodsFormat(sku.getFormat());
        // content.setFee(cart.getNumber() *price);
        content.setGoodsFlavor("");// 添加口味
        content.setOrderID(orderID);
        content.setActivityID(rule.getId());
        content.setActivityName("ThGroupBuyingRules");
        content.setSkuID(sku.getID());
        content.setGroupID(groupID);
        contentList.add(content);
        return contentList;
    }

    private List<OrderContent> orderBuyContentAdd(int orderID, ThGroupBuyingRules rule, int num) {
        List<OrderContent> contentList = new ArrayList<OrderContent>();
        OrderContent content = new OrderContent();
        int goodsId = rule.getGoodsId();
        int shopId = rule.getShopId();
        int skuId = rule.getSkuId();
        ThSku gPrice = goodsManager.goodsPrice(goodsId, rule.getGoodsFormat());
        String fprice = String.valueOf(gPrice.getPrice());
        BigDecimal fpriceBD = new BigDecimal(fprice);
        int price = fpriceBD.intValue() * 100;
        Goods goods = goodsManager.goodsDetail(goodsId);
        Shop shop = goodsManager.shopDetail(shopId);

        content.setGoodsID(goodsId);

        int fee = price * num;

        BigDecimal bd = new BigDecimal(fee);
        bd = bd.movePointLeft(2);
        float floatFee = bd.floatValue();

        BigDecimal priceBD = new BigDecimal(price);
        priceBD = priceBD.movePointLeft(2);
        float floatPrice = Float.parseFloat(priceBD.toString());

        content.setGoodsTitle(goods.getGoodsTitle());
        content.setGoodsNumber(num);
        content.setShopName(shop.getShopName());
        content.setGoodsFormat(rule.getGoodsFormat());
        content.setGoodsPrice(floatPrice);
        content.setFee(floatFee);
        content.setGoodsPicture(GoodsParse.getOneGoodsPicture(goods.getGoodsPicture()));
        content.setGoodsFlavor("");// 添加口味
        content.setOrderID(orderID);
        content.setShopID(shop.getShopID());
        content.setActivityName("ThGoods");
        content.setSkuID(skuId);
        contentList.add(content);
        return contentList;
    }

    // 根据判断今日有没有购买
    public int activityOrderNumber(Cart cart, ActivityPrice ap) {
        int number = 0;
        if (ap == null) {
            return number;
        }
        List<Order> activityOrder = orderManager.activityOrder(ap.getStartTime(), ap.getEndTime(),
                cart.getUserID());
        for (Order order : activityOrder) {
            if (order.getStation() == 0) {
                continue;
            }
            OrderContent oc = orderManager.getActivityOrderContent(cart.getGoodsID(),
                    cart.getGoodsFormat(), order.getOrderID());
            if (oc != null) {
                number += oc.getGoodsNumber();
            }
        }
        return number;
    }

    public int checkNumberLimit(Cart cart) {
        /*
         * -3:商品库存不足； -4:活动商品库存不足； -5:超过限购数量；
         */
        int tag = 1;
        /*
         * ：判断该商品是否是活动商品 是：判断超过活动商品库存 判断超过个人限购 不是：判断是否超过商品库存
         */

        ActivityPrice ap = orderManager.getActivityPriceBySkuID(cart.getSkuID());
        if (ap != null) {
            int orderActivityNumber = activityOrderNumber(cart, ap);// 已经购买的数量
            if ((ap.getNumber() - ap.getSellOut()) < cart.getNumber()) {// 大于活动库存
                tag = -4;
            } else if (ap.getLimit() < (cart.getNumber() + orderActivityNumber)) {// 大于个人限购
                tag = -5;
            }
        }

        return tag;
    }

    // 库存
    // public boolean goodsStore(int cartID) {
    // Cart cart = cartManager.cartDetail(cartID);
    // ActivityPrice ap =
    // orderManager.getActivityPrice(cart.getGoodsID(),cart.getGoodsFormat());
    // if (ap != null) {
    // if (ap.getNumber() - ap.getSellOut() < cart.getNumber()) {
    // return true;
    // }
    // } else {
    // Goods goods = goodsManager.goodsDetail(cart.getGoodsID());
    // if (goods.getGoodsNumber() < cart.getNumber()) {
    // return true;// 商品库存不足
    // }
    // }
    // return false;
    // }

    // 创建物流订单
    private Order createOrderForGroup(int userID, int shopId) {
        Order order = new Order();
        order.setPin(0);// 全部为一个商家，不需要拼包
        order.setShopID(shopId);
        order.setStation(0);// 设置订单状态
        order.setUserID(userID);// 用户ID
        return order;
    }

    // 创建订单物流
    private OrderLogistic createOrderLogisticForGroup(int orderID, int addressID, int selfAddId,
                                                      int goodsID, int number) {
        OrderLogistic logistic = new OrderLogistic();

        // 获取地址
        if (addressID != 0) {
            DeliveryAddr delivery = accountManager.getAddr(addressID);
            if (delivery != null) {
                logistic = addLogisticForGroup(delivery, goodsID, number);
            }
        }
        //自提地址
        if (selfAddId != 0) {
            ThGroupDeliveryAddr addr = directoryManager.getGroupDeliveryInfoById(selfAddId);
            if (addr != null) {
                logistic.setFee(0);
                ThDirectSupply supply = directoryManager.getDirectSupplyById(addr
                        .getDirectSupplyId() + "");
                logistic.setFromAddress(supply.getPickupPoint());
                logistic.setReceiver(addr.getName());// 收货人姓名
                logistic.setReceiverPhone(addr.getPhone());// 收货人手机号
                logistic.setReceiverAddress(supply.getBlockName() + addr.getAddress());
                logistic.setWeight("0");

                float allWeight = 0;// 商品的重量
                Goods goods = goodsManager.goodsDetail(goodsID);// 商品
                allWeight += number * (goods.getGoodsWeight());// 商品的总重量
                logistic.setWeight(allWeight + "");
            }
        }
        logistic.setOrderID(orderID);
        return logistic;
    }

    // 创建订单内容
    public List<OrderContent> createOrderContent(int orderID, List<CSG> list) {
        List<OrderContent> contentList = new ArrayList<OrderContent>();
        for (CSG csg : list) {
            OrderContent content = new OrderContent();
            Goods goods = goodsManager.goodsDetail(csg.getGoodsID());
            Cart cart = cartManager.cartDetail(csg.getCartID());
            Shop shop = goodsManager.shopDetail(csg.getShopID());

            content.setGoodsID(goods.getGoodsID());

            /*
             * 判断订单当前是否在活动
             */
            double price = 0;
            ActivityPrice ap = orderManager.getActivityPriceBySkuID(cart.getSkuID());
            if (ap != null) {
                price = ap.getStartPrice();
            } else {
                // 根据规格获取价格
                ThSku gp = goodsManager.skuGet(cart.getSkuID());
                price = gp.getPrice();
            }
            float fee = (float) (Math.round((cart.getNumber() * price) * 100)) / 100;// 输出123.24;

            content.setGoodsTitle(goods.getGoodsTitle());
            content.setGoodsNumber(cart.getNumber());
            content.setShopName(shop.getShopName());
            content.setGoodsFormat(cart.getGoodsFormat());
            content.setGoodsPrice(price);
            content.setFee(fee);
            // content.setFee(cart.getNumber() *price);
            content.setGoodsPicture(GoodsParse.getOneGoodsPicture(goods.getGoodsPicture()));
            content.setGoodsFlavor(cart.getGoodsFlavor());// 添加口味
            content.setOrderID(orderID);
            content.setShopID(shop.getShopID());
            contentList.add(content);
        }

        return contentList;
    }

    // 创建订单的物流
    public OrderLogistic addLogisticForGroup(DeliveryAddr addr, int goodsID, int number) {
        OrderLogistic ol = new OrderLogistic();
        float minPostage = 10000000;// 最低邮费(这是先设定的)

        float allFee = 0;// 所有费用
        float allWeight = 0;// 商品的重量

        Goods goods = goodsManager.goodsDetail(goodsID);// 商品
        double price = goods.getGoodsPrice();// 商品价格
        double goodsFee = number * price;// 商品的费用

        allFee += goodsFee;// 总价格
        allWeight += number * (goods.getGoodsWeight());// 商品的总重量

        int patternID = goods.getGoodsLogistic();// 物流模版ID
        float postage = postageCaculate(allFee, allWeight, patternID, addr);
        if (postage == 0) {
            minPostage = 0;// 已经免费了,就不需要再计算下去了
        } else {
            if (postage <= minPostage) {
                minPostage = postage;
            }
        }

        // 设置邮费
        ol.setFee(minPostage);

        String fromAddress = "北京市金融街园中园";
        ol.setFromAddress(fromAddress);

        ol.setReceiver(addr.getName());// 收货人姓名
        ol.setReceiverPhone(addr.getPhone());// 收货人手机号

        String county = "";
        if (addr.getCounty() != null) {
            county = addr.getCounty();// 防止县为空
        }

        String receiverAddress = addr.getProvince() + addr.getCity() + county + addr.getAddress();
        ol.setReceiverAddress(receiverAddress);

        ol.setWeight(allWeight + "");
        return ol;
    }

    public int postageCaculate(float allMoney, float allWeight, int patternID, DeliveryAddr addr) {
        /*
         * 是否存在包邮 1:存在，且达到包邮的条件 运费为 0； 2: 达不到条件的情况下查看是否是其他区域的计算方式 2.1
         * 是其他区域，根据其他区域计算邮费 2.2 不是其他区域就是全国的计算方式计算邮费
         */

        float mailFee;
        // 包邮的地区
        AreaPostage ap = logiManager.getPostage(patternID, addr.getProvince(), addr.getCity());
        AreaPostage apNation = null;
        if (ap != null) {
            mailFee = ap.getPostage();// 其他区域模版
        } else {
            AreaPostage apNO = logiManager.getNoPostage(patternID, addr.getProvince(),
                    addr.getCity());
            if (apNO != null) {
                mailFee = -1;// 不包邮
            } else {
                apNation = logiManager.getNationPostage(patternID);
                if (apNation != null) {
                    mailFee = apNation.getPostage();// 全国模版
                } else {
                    mailFee = -1;// 不包邮
                }
            }
        }
        if (mailFee == -1 || mailFee > allMoney) {// 不包邮的情况下
            // 无法包邮
            LogisticPatternExc logiExc = logiManager.getPatternExc(patternID, addr.getProvince(),
                    addr.getCity());
            if (logiExc != null) {
                return weightCostNoPostage(logiExc.getInitKG(), logiExc.getInitFee(),
                        logiExc.getAddKG(), logiExc.getAddFee(), allWeight);
            } else {
                LogisticPattern logi = logiManager.getPattern(patternID);
                return weightCostNoPostage(logi.getInitKG(), logi.getInitFee(), logi.getAddKG(),
                        logi.getAddFee(), allWeight);
            }
        } else {
            // //允许包邮
            // LogisticPatternExc logiExc = logiManager.getPatternExc(patternID,
            // addr.getProvince(), addr.getCity());
            // if(logiExc!=null){
            // return weightCostWithPostage(logiExc.getInitKG(),
            // logiExc.getInitFee(), logiExc.getAddKG(),logiExc.getAddFee(),
            // allWeight);
            // }else{
            // LogisticPattern logi = logiManager.getPattern(patternID);
            // return weightCostWithPostage(logi.getInitKG(), logi.getInitFee(),
            // logi.getAddKG(),logi.getAddFee(), allWeight);
            // }

            if (ap != null) {
                return weightCostWithPostage(ap.getInitKG(), ap.getAddKG(), ap.getAddFee(),
                        allWeight);
            } else {
                return weightCostWithPostage(apNation.getInitKG(), apNation.getAddKG(),
                        apNation.getAddFee(), allWeight);
            }

        }

        // System.out.println("---包邮费用---"+mailFee);
        // if(ap!=null&&ap.getPostage()<allMoney){
        // return 0;
        // }
        //
        // LogisticPatternExc logiExc = logiManager.getPatternExc(patternID,
        // addr.getProvince(), addr.getCity());
        // if(logiExc!=null){
        // return weightCost(logiExc.getInitKG(), logiExc.getInitFee(),
        // logiExc.getAddKG(),logiExc.getAddFee(), allWeight);
        // }else{
        // LogisticPattern logi = logiManager.getPattern(patternID);
        // return weightCost(logi.getInitKG(), logi.getInitFee(),
        // logi.getAddKG(),logi.getAddFee(), allWeight);
        // }

    }

    // 无免邮重量消费
    public int weightCostNoPostage(float initKG, float initFee, float addKG, float addFee,
                                   float goodsWeight) {
        float price = 0;
        float goodsKG = goodsWeight / 1000;// 克转化为千克
        if (goodsKG < initKG) {
            price = initFee;
        } else {
            int iKG = (int) Math.ceil(goodsKG);
            price = initFee + ((iKG - initKG) / addKG) * addFee;
        }
        return (int) price;
    }

    // 有包邮重量消费重量消费
    public int weightCostWithPostage(float initKG, float addKG, float addFee, float goodsWeight) {
        float price = 0;
        float goodsKG = goodsWeight / 1000;// 克转化为千克
        if (goodsKG < initKG) {
            price = 0;
        } else {
            int iKG = (int) Math.ceil(goodsKG);
            price = ((iKG - initKG) / addKG) * addFee;
        }
        return (int) price;
    }

    // 订单提交
    public void orderCommit(HttpServletRequest request, HttpServletResponse response) {
        OrderParam param = (OrderParam) RemoteUtil.request(request, new OrderParam());
        valiTag = accountManager.validate(param.getUserID(), param.getUserToken());
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        String orderContent = param.getOrderContent();
        String orderArr[] = orderContent.split("\\*");

        boolean calculateTag = true;
        float allMoney = 0;

        // 获取所有订单，获取订单里面所有的商品，获取商品所有的
        List<OrderObject> list = new ArrayList<OrderObject>();

        // 礼品卡总金额
        float totalGiftCardMoney = 0;

        for (String aOrder : orderArr) {
            String[] arr = aOrder.split("&");

            int orderID;// 订单ID
            int couponID;// 代金券ID
            float giftcardMoney;// 礼品卡金额
            float couponFee = 0;// 代金券金额
            float money;// 现金金额
            String message;// 留言
            String invoice;// 发票
            String congra;// 贺词
            String deliveryTime;// 发货时间

            orderID = Integer.parseInt(arr[0]);// 订单ID
            Order order = orderManager.getOrder(orderID);
            couponID = Integer.parseInt(arr[1]);// 代金券ID
            giftcardMoney = Float.parseFloat(arr[2]);// 礼品卡金额
            money = (float) order.getFee();// 现金
            message = arr[4];// 留言
            invoice = arr[5];// 发票
            congra = arr[6];// 贺词
            deliveryTime = arr[7];// 发货时间

            totalGiftCardMoney += giftcardMoney;

            if (deliveryTime.equals("0")) {
                deliveryTime = "工作日、双休日、假日均可送货^不限";
            }

            if (message.equals("0")) {
                message = null;
            }
            if (invoice.equals("0")) {
                invoice = null;
            }
            if (congra.equals("0")) {
                congra = null;
            }

            allMoney += money;// 计算一下现金的总价格

            OrderObject obj = new OrderObject();
            obj.setOrderID(orderID);
            obj.setCouponID(couponID);
            obj.setGiftcardMoney(giftcardMoney);
            obj.setMoney(money);
            obj.setMessage(message);
            obj.setInvoice(invoice);
            obj.setCongratulations(congra);
            obj.setCouponFee(0);
            obj.setDeliveryTime(deliveryTime);

            if (couponID != 0) {// 传了代金券
                WalletCoupon coupon = walletManager.getCoupon(couponID, param.getUserID());
                if (coupon.getValid() == 1) {// 表示代金券还有效
                    couponFee = coupon.getMoney();
                    obj.setCouponFee(couponFee);// 代金券金额
                }
            }

            list.add(obj);// 获取一个订单的数组

            // 计算的费用
            float calculateFee = couponFee + giftcardMoney + money;

            // 订单的费用
            System.out.println(orderID);
            double orderFee = order.getFee();// 订单的总费用
            orderFee = (float) (Math.round(orderFee * 100) / 100.0);// 保留两位小数

            if (calculateFee < orderFee) {// 计算的价格和订单的价格相同
                calculateTag = false;
                break;
            }
        }

        WalletGiftCardCount count = walletManager.getgiftCardCount(param.getUserID());
        if (count.getMoney() < totalGiftCardMoney) {
            RemoteUtil.response(response, null, -1, "操作失败");
            return;
        }

        if (!calculateTag) {// 计算价格异常
            RemoteUtil.response(response, null, -1, "操作失败");
            return;
        }

        // 获取客户端的ip
        String ip = getIpAddr(request);

        // 遍历订单内容
        String orderID = "";
        for (OrderObject obj : list) {
            orderID += obj.getOrderID() + ";";
            // 疯抢库存检测
            int flagGroup = checkPanic(obj.getOrderID(), param.getUserID());
            if (flagGroup < 0) {
                RemoteUtil.response(response, null, flagGroup, "参加疯抢失败");
                return;
            }
        }

        if (allMoney != 0) {// 有现金支付
            String out_trade_no = WeixinUtils.getOut_trade_no();// 交易号
            TradeNo no = generateTradeNo(out_trade_no, orderID, param.getUserID(),
                    (int) (allMoney * 100));
            // TODO 完成支付单数据的填写
            orderManager.addTradeNo(no);// 插入交易号

            switch (param.getFeeType()) {
                case 1:// 支付宝支付
                    aliPay(allMoney + "", list, param.getUserID(), orderID, response, out_trade_no);
                    break;
                case 2:// 微信App支付
                {
                    String body = "乡味汇订单";

                    BigDecimal b1 = new BigDecimal(allMoney);
                    BigDecimal b2 = new BigDecimal(100);
                    int totalFee = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).intValue();

                    wxAppPay(totalFee, body, ip, out_trade_no, request, response, list,
                            param.getUserID());
                    break;
                }
                case 6:// 微信公众号支付（前面的数字留给applePay、银联支付等）
                {
                    String body = "乡味汇订单";

                    BigDecimal b1 = new BigDecimal(allMoney);
                    BigDecimal b2 = new BigDecimal(100);
                    int totalFee = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).intValue();

                    wxOAPay(totalFee, body, ip, out_trade_no, request, response, list,
                            param.getUserID());
                    break;
                }
                case 7: // 乡币支付
                {
                    System.out.println("使用乡币支付");
                    logger.info("使用乡币支付");
                    // 获取订单需支付金额
                    BigDecimal orderTotalAmounts = new BigDecimal(allMoney);
                    int totalFee = orderTotalAmounts.multiply(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP).intValue();
                    // 获取乡币账户余额
                    ThHcWallet userWallet = walletManager.getWalletByUser(param.getUserID());
                    // 账户金额是否足够支付订单
                    int availeAmounts = userWallet.getAvaileAmounts();
                    if (availeAmounts < totalFee) {
                        RemoteUtil.response(response, "", -1, "可用乡币余额不足");
                        return;
                    }
                    System.out.println("钱包余额：" + availeAmounts + "，订单金额：" + totalFee);
                    logger.info("钱包余额：" + availeAmounts + "，订单金额：" + totalFee);
                    // 扣款
                    boolean oTag = walletManager.hcWalletAvaileUpdateByID(availeAmounts - totalFee,
                            userWallet.getId());
                    if (oTag) {
                        System.out.println("扣款成功");
                        logger.info("扣款成功");
                        // 支付完成的后续动作
                        for (OrderObject obj : list) {
                            // 修改状态为1
                            orderManager.updateOrderStation(obj.getOrderID(), 1);
                            logger.info("遍历中..订单编号：" + obj.getOrderID());
                            int station = 2; // station= 2 表示待发货
                            Order order = orderManager.getOrder(obj.getOrderID());
                            System.out.println("有没有找到订单啊2：" + order.getUserID());
                            logger.info("有没有找到订单啊：" + order.getUserID() + "，状态："
                                    + order.getStation());
                            if (order == null || order.getStation() != 1) {
                                continue;
                            }
                            int userId = order.getUserID();
                            BigDecimal fee = new BigDecimal(order.getFee());
                            int feeInt = fee.multiply(new BigDecimal(100))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).intValue();
                            System.out.println("遍历中..子单金额：" + feeInt);
                            logger.info("遍历中..子单金额：" + feeInt);
                            // 获取用户信息
                            ClientInfo clientInfo = accountManager.getInfo(userId);
                            // 创建支出记录
                            ThOutcomeRecord outcomeRecord = new ThOutcomeRecord();
                            outcomeRecord.setAmounts(feeInt);
                            outcomeRecord.setCreatedAt(new Date(System
                                    .currentTimeMillis()));
                            outcomeRecord.setOrderId(obj.getOrderID());
                            outcomeRecord.setSn("HCOUT" + System.currentTimeMillis());
                            outcomeRecord.setUserId(param.getUserID());
                            outcomeRecord.setUserName(clientInfo.getName());
                            outcomeRecord.setWalletId(userWallet.getId());
                            outcomeRecord.setState(1); // 已支付
                            walletManager.outcomeRecordsCreate(outcomeRecord);

                            // 添加销量
                            updateSellout(order, userId);

                            // 修改礼品金额
                            float giftCardMoney = order.getGiftcardFee();
                            int userID = order.getUserID();
                            orderManager.deleteCouponCount(userID, giftCardMoney);
                            logger.info("提交订单：修改礼品金额成功");
                            // 修改订单的状态和交易的类型和交易的时间
                            int feeType = 7;
                            orderManager.updateOrderStationAndTransaction(obj.getOrderID(),
                                    station, feeType, out_trade_no);
                            logger.info("提交订单：修改订单状态（" + obj.getOrderID() + "," + station + ","
                                    + feeType + "," + out_trade_no + "）");
                            // 修改付款订单的时间
                            orderManager.updateOrderTime(obj.getOrderID(), 2,
                                    System.currentTimeMillis());// 修改订单付款的时间
                            payNews(order.getUserID(), obj.getOrderID());

                            // 加入分销信息
                            addSURecord(obj.getOrderID(), order.getUserID());
                        }
                        RemoteUtil.response(response, "", 1, "操作成功");
                    } else {
                        logger.info("扣款失败，账号：" + userWallet.getId());
                        RemoteUtil.response(response, "", -1, "扣款失败");
                    }
                }
            }

        }

        // 修改订单状态，和删除库存
        for (OrderObject obj : list) {
            // 如果订单的状态为未支付，即station=1
            float wxFee = 0;
            float zfbFee = 0;
            int station = 2;// 已支付，待发货
            int transactionType = 0;// 交易类型
            float couponFee = obj.getCouponFee();
            float giftcardFee = obj.getGiftcardMoney();

            if (obj.getMoney() == 0) {
                /*
                 * 直接修改订单状态为已经支付
                 */
                station = 2;// 已支付，待发货
                transactionType = 0;// 交易类型

                // 修改礼品金额
                float giftCardMoney = obj.getGiftcardMoney();
                orderManager.deleteCouponCount(param.getUserID(), giftCardMoney);

                // 修改付款订单的时间
                orderManager.updateOrderTime(obj.getOrderID(), 2, System.currentTimeMillis());

                // 发消息
                payNews(param.getUserID(), obj.getOrderID());
                RemoteUtil.response(response, null, 1, "操作成功");

            } else {
                /*
                 * 修改订单状态为未支付
                 */
                station = 1;// 未支付
                transactionType = param.getFeeType();// 交易类型
                if (transactionType == 1) {
                    zfbFee = obj.getMoney();
                } else {
                    wxFee = obj.getMoney();
                }
            }
            // 乡币支付，状态默认为2 #3924-13
            if (transactionType == 7) {
                station = 2;
            }
            // 修改订单状态
            orderManager.orderUpdate(wxFee, zfbFee, couponFee, giftcardFee, obj.getMessage(),
                    station, obj.getOrderID(), transactionType, obj.getInvoice(),
                    obj.getCongratulations(), obj.getDeliveryTime());
            // 删除购物车、修改库存
            if (StringUtils.isBlank(param.getOrderID())) {
                //非待付款页面下单
                afterOrderCommit(obj.getOrderID(), param.getUserID(), true);
            } else {
                //待付款页面下单
                afterOrderCommit(obj.getOrderID(), param.getUserID(), false);
            }

            // 修改代金券失效
            if (obj.getCouponID() != 0) {
                walletManager.updateCouponInvalid(obj.getCouponID(), param.getUserID());
            }
            // 修改订单时间
            orderManager.updateOrderTime(obj.getOrderID(), 1, System.currentTimeMillis());// 修改订单提交的时间

            // 添加商店用户
            Order order = orderManager.getOrder(obj.getOrderID());
            ClientAccount account = accountManager.getAccount(null, order.getUserID());
            if (account != null) {
                ClientInfo info = accountManager.getInfo(order.getUserID());
                addShopClient(order.getShopID(), order.getUserID(), account.getPhone(),
                        info.getName());
            }
        }
    }

    // 订单提交
    /**
     * @param request
     * @param response
     */
    /**
     * @param request
     * @param response
     */
    public void groupOrdersCommit(HttpServletRequest request, HttpServletResponse response) {

        //【1】身份验证
        OrderParam param = (OrderParam) RemoteUtil.request(request, new OrderParam());
        valiTag = accountManager.validate(param.getUserID(), param.getUserToken());
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        /*
         * 订单提交内容 1:获取所有的订单ID； 2：计算所有订单的总费用，和提交的总费用对比一下；相等，订单提交成功，不相等，订单提交失败；
         */
        String orderContent = param.getOrderContent();
        String orderArr[] = orderContent.split("\\*");
        boolean calculateTag = true;
        float allMoney = 0;
        // 获取所有订单，获取订单里面所有的商品，获取商品所有的
        List<OrderObject> list = new ArrayList<OrderObject>();
        // 礼品卡总金额
        float totalGiftCardMoney = 0;

        //【2】初始化订单内容
        for (String aOrder : orderArr) {
            String[] arr = aOrder.split("&");
            float couponFee = 0;// 代金券金额
            int orderID = Integer.parseInt(arr[0]);// 订单ID
            int couponID = Integer.parseInt(arr[1]);// 代金券ID
            float giftcardMoney = Float.parseFloat(arr[2]);// 礼品卡金额
            float money = Float.parseFloat(arr[3]);// 现金
            totalGiftCardMoney += giftcardMoney;
            allMoney += money;// 计算一下现金的总价格

            //发货时间
            String deliveryTime = arr[7];
            if (deliveryTime.equals("0")) {
                deliveryTime = "工作日、双休日、假日均可送货^不限";
            }
            //留言
            String message = arr[4];
            if (message.equals("0")) {
                message = null;
            }
            //发票
            String invoice = arr[5];
            if (invoice.equals("0")) {
                invoice = null;
            }
            //贺词
            String congra = arr[6];
            if (congra.equals("0")) {
                congra = null;
            }

            OrderObject obj = new OrderObject();
            obj.setOrderID(orderID);
            obj.setCouponID(couponID);
            obj.setGiftcardMoney(giftcardMoney);
            obj.setMoney(money);
            obj.setMessage(message);
            obj.setInvoice(invoice);
            obj.setCongratulations(congra);
            obj.setCouponFee(0);
            obj.setDeliveryTime(deliveryTime);

            if (couponID != 0) {// 传了代金券
                WalletCoupon coupon = walletManager.getCoupon(couponID, param.getUserID());
                if (coupon.getValid() == 1) {// 表示代金券还有效
                    couponFee = coupon.getMoney();
                    obj.setCouponFee(couponFee);// 代金券金额
                }
            }

            list.add(obj);// 获取一个订单的数组
            // 计算的费用
            float calculateFee = couponFee + giftcardMoney + money;
            // 订单的费用
            Order order = orderManager.getOrder(orderID);
            double orderFee = order.getFee();// 订单的总费用
            orderFee = (float) (Math.round(orderFee * 100) / 100);// 保留两位小数
            if (calculateFee < orderFee) {// 计算的价格和订单的价格相同
                calculateTag = false;
                break;
            }
        }

        WalletGiftCardCount count = walletManager.getgiftCardCount(param.getUserID());
        if (count.getMoney() < totalGiftCardMoney) {
            RemoteUtil.response(response, null, -1, "操作失败");
            return;
        }

        if (!calculateTag) {// 计算价格异常
            RemoteUtil.response(response, null, -1, "操作失败");
            return;
        }

        // 获取客户端的ip
        String ip = getIpAddr(request);

        // 遍历订单内容
        String orderID = "";
        for (OrderObject obj : list) {
            orderID += obj.getOrderID() + ";";
            // 开启新的团购，如果是参加已有的团购这一步跳过
            int flagGroup = startGroup(obj.getOrderID(), param.getUserID());
            if (flagGroup < 0) {
                RemoteUtil.response(response, null, flagGroup, "开团失败");
                return;
            }
        }

        //如果订单有现金支付，判断是微信还是支付宝支付， 调用相应的接口 如果订单没有现金支付，直接修改订单的状态
        if (allMoney != 0) {// 有现金支付
            String out_trade_no = WeixinUtils.getOut_trade_no();// 交易号
            TradeNo no = generateTradeNo(out_trade_no, orderID, param.getUserID(),
                    (int) (allMoney * 100));
            // TODO 完成支付单数据的填写
            orderManager.addTradeNo(no);// 插入交易号

            switch (param.getFeeType()) {
                case 1:// 支付宝支付
                    aliPay(allMoney + "", list, param.getUserID(), orderID, response, out_trade_no);
                    break;
                case 2:// 微信App支付
                {
                    String body = "乡味汇订单";

                    BigDecimal b1 = new BigDecimal(allMoney);
                    BigDecimal b2 = new BigDecimal(100);
                    int totalFee = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).intValue();

                    wxAppPay(totalFee, body, ip, out_trade_no, request, response, list,
                            param.getUserID());
                    break;
                }
                case 6:// 微信公众号支付（前面的数字留给applePay、银联支付等）
                {
                    String body = "乡味汇订单";

                    BigDecimal b1 = new BigDecimal(allMoney);
                    BigDecimal b2 = new BigDecimal(100);
                    int totalFee = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).intValue();

                    wxOAPay(totalFee, body, ip, out_trade_no, request, response, list,
                            param.getUserID());
                    break;
                }
                case 7: // 乡币支付
                {
                    // 获取订单需支付金额
                    BigDecimal orderTotalAmounts = new BigDecimal(allMoney);
                    int totalFee = orderTotalAmounts.multiply(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP).intValue();
                    // 获取乡币账户余额
                    ThHcWallet userWallet = walletManager.getWalletByUser(param.getUserID());
                    // 账户金额是否足够支付订单
                    int availeAmounts = userWallet.getAvaileAmounts();
                    if (availeAmounts < totalFee) {
                        RemoteUtil.response(response, "", -1, "可用乡币余额不足");
                    }
                    System.out.println("钱包余额：" + availeAmounts + "，订单金额：" + totalFee);
                    // 扣款
                    boolean oTag = walletManager.hcWalletAvaileUpdateByID(availeAmounts - totalFee,
                            userWallet.getId());
                    if (oTag) {
                        // 支付完成的后续动作
                        for (OrderObject obj : list) {
                            orderManager.updateOrderStation(obj.getOrderID(), 1);
                            int station = 2; // station= 2 表示待发货
                            Order order = orderManager.getOrder(obj.getOrderID());
                            System.out.println("订单编号：" + obj.getOrderID());
                            if (order == null || order.getStation() != 1) {
                                continue;
                            }
                            int userId = order.getUserID();
                            BigDecimal fee = new BigDecimal(order.getFee());
                            int feeInt = fee.multiply(new BigDecimal(100))
                                    .setScale(2, BigDecimal.ROUND_HALF_UP).intValue();

                            System.out.println("子单金额：" + feeInt);

                            // 获取用户信息
                            ClientInfo clientInfo = accountManager.getInfo(userId);
                            // 创建支出记录
                            ThOutcomeRecord outcomeRecord = new ThOutcomeRecord();
                            outcomeRecord.setAmounts(feeInt);
                            outcomeRecord.setCreatedAt(new Date(System
                                    .currentTimeMillis()));
                            outcomeRecord.setOrderId(obj.getOrderID());
                            outcomeRecord.setSn("HCOUT" + System.currentTimeMillis());
                            outcomeRecord.setUserId(param.getUserID());
                            outcomeRecord.setUserName(clientInfo.getName());
                            outcomeRecord.setWalletId(userWallet.getId());
                            outcomeRecord.setState(1); // 已支付
                            walletManager.outcomeRecordsCreate(outcomeRecord);

                            // 添加销量
                            updateSellout(order, userId);

                            // 修改礼品金额
                            float giftCardMoney = order.getGiftcardFee();
                            int userID = order.getUserID();
                            orderManager.deleteCouponCount(userID, giftCardMoney);

                            // 修改订单的状态和交易的类型和交易的时间
                            int feeType = (7);
                            orderManager.updateOrderStationAndTransaction(obj.getOrderID(),
                                    station, feeType, out_trade_no);
                            // 修改付款订单的时间
                            orderManager.updateOrderTime(obj.getOrderID(), 2,
                                    System.currentTimeMillis());// 修改订单付款的时间
                            payNews(order.getUserID(), obj.getOrderID());
                        }
                    }
                    RemoteUtil.response(response, "", 1, "操作成功");
                }
            }
        }

        // 修改订单状态，和删除库存
        for (OrderObject obj : list) {
            // 如果订单的状态为未支付，即station=1
            float wxFee = 0;
            float zfbFee = 0;
            int station = 2;// 已支付，待发货
            int transactionType = 0;// 交易类型
            float couponFee = obj.getCouponFee();
            float giftcardFee = obj.getGiftcardMoney();

            if (obj.getMoney() == 0) {
                /*
                 * 直接修改订单状态为已经支付
                 */
                station = 2;// 已支付，待发货
                transactionType = 0;// 交易类型

                // 修改礼品金额
                float giftCardMoney = obj.getGiftcardMoney();
                orderManager.deleteCouponCount(param.getUserID(), giftCardMoney);

                // 修改付款订单的时间
                orderManager.updateOrderTime(obj.getOrderID(), 2, System.currentTimeMillis());

                // 发消息
                payNews(param.getUserID(), obj.getOrderID());
                RemoteUtil.response(response, null, 1, "操作成功");

            } else {
                /*
                 * 修改订单状态为未支付
                 */
                station = 1;// 未支付
                transactionType = param.getFeeType();// 交易类型
                if (transactionType == 1) {
                    zfbFee = obj.getMoney();
                } else {
                    wxFee = obj.getMoney();
                }
            }
            // 乡币支付，状态默认为2 #3924-13
            if (transactionType == 7) {
                station = 2;
            }
            // 修改订单状态
            orderManager.orderUpdate(wxFee, zfbFee, couponFee, giftcardFee, obj.getMessage(),
                    station, obj.getOrderID(), transactionType, obj.getInvoice(),
                    obj.getCongratulations(), obj.getDeliveryTime());
            // 修改代金券失效
            if (obj.getCouponID() != 0) {
                walletManager.updateCouponInvalid(obj.getCouponID(), param.getUserID());
            }
            // 修改订单时间
            orderManager.updateOrderTime(obj.getOrderID(), 1, System.currentTimeMillis());// 修改订单提交的时间

            // 添加商店用户
            Order order = orderManager.getOrder(obj.getOrderID());
            ClientAccount account = accountManager.getAccount(null, order.getUserID());
            if (account != null) {
                ClientInfo info = accountManager.getInfo(order.getUserID());
                addShopClient(order.getShopID(), order.getUserID(), account.getPhone(),
                        info.getName());
            }
        }
    }

    // 订单数量
    public void orderNumber(HttpServletRequest request, HttpServletResponse response) {
        String userID = request.getParameter("userID");
        List<JsonOrderNumber> numberList = new ArrayList<JsonOrderNumber>();

        if (userID == null) {
            RemoteUtil.response(response, null, 0, "无数据");
        }

        for (int i = 1; i <= 4; i++) {
            int k = i;
            /*
             * 1:待支付 2：待发货 3：待收获 5：待评价 7:售后退款
             */
            if (i == 4) {
                k = 5;
            }
            JsonOrderNumber orderNumber = new JsonOrderNumber();
            orderNumber.setStation(k);
            int number = orderManager.orderNumber(Integer.parseInt(userID), k);
            orderNumber.setNumber(number);
            numberList.add(orderNumber);
        }
        /*
         * 售后退款的数量
         */
        numberList.add(refundNumber(Integer.parseInt(userID)));
        RemoteUtil.response(response, numberList, 1, "返回成功");
    }

    // 订单退款
    public void orderRefund(HttpServletRequest request, HttpServletResponse response) {
        String orderID = request.getParameter("orderID");
        String userID = request.getParameter("userID");
        String message = request.getParameter("message");

        Order order = orderManager.getOrder(Integer.parseInt(orderID));
        if (Integer.parseInt(userID) != order.getUserID()) {
            RemoteUtil.response(response, null, 0, "身份异常");
            return;
        }

        OrderTime orderTime = orderManager.getOrderTime(Integer.parseInt(orderID));
        OrderLogistic logi = orderManager.getOrderLogistic(Integer.parseInt(orderID));
        ClientAccount account = accountManager.getAccount(null, order.getUserID());

        boolean allowRefund = false;
        if (order.getStation() == 2) {
            allowRefund = true;
        }

        if (order.getStation() == 6) {
            long interval = 7 * 24 * 60 * 60 * 1000l;
            long time = System.currentTimeMillis() - interval;
            if (orderTime.getClientConfirmTime() > time) {
                allowRefund = true;
            }
        }

        if (allowRefund) {
            // 待发货和交易完成的情况下运行退款
            Refund refund = new Refund();

            refund.setOrderID(Integer.parseInt(orderID));
            refund.setOrderFee(order.getFee());
            refund.setLogiFee(logi.getFee());

            refund.setPhone(account.getPhone());
            refund.setShopID(order.getShopID());
            refund.setStation(0);
            refund.setUserID(order.getUserID());
            refund.setClientMessage(message);

            orderManager.addRefund(refund);

            /*
             * 修改订单的状态售后退款
             */
            orderManager.updateOrderStation(Integer.parseInt(orderID), 7);
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }

    }

    public JsonOrderNumber refundNumber(int userID) {
        JsonOrderNumber jn = new JsonOrderNumber();
        int number = orderManager.unFinishRefund(userID);
        jn.setStation(7);
        jn.setNumber(number);
        return jn;
    }

    ;

    public void wxAppPay(int totalPrice, String body, String ip, String out_trade_no,
                         HttpServletRequest request, HttpServletResponse response,
                         List<OrderObject> list, int userID) {
        System.out.println("----创建微信预付定单-----");
        try {
            System.out.println("totalPrice--->" + totalPrice);
            System.out.println("product_name--->" + body);
            System.out.println("ip--->" + ip);
            /*
             * 调用统一支付接口
             */

            String notifyUrl = Path.weixin_pay_notifyurl_goods;

            Map<String, String> map = WeixinUtils.payUnifiedorder(WXPayType.AppPay, body,
                    totalPrice, ip, out_trade_no, notifyUrl, null);
            TreeMap<String, String> outParams = new TreeMap<String, String>();
            if (null != map) {
                String app_id = map.get("appid");
                /*
                 * 获取预支付id
                 */
                String prepayid = map.get("prepay_id");
                /**
                 * 创建预支付sign签名
                 */
                String noceStr = RandomStringGenerator.getRandomStringByLength(32);
                String timeStamp = String.valueOf((System.currentTimeMillis() / 1000));
                List<NameValuePair> signParams = new LinkedList<NameValuePair>();
                signParams.add(new BasicNameValuePair("appid", app_id));
                signParams.add(new BasicNameValuePair("noncestr", noceStr));
                signParams.add(new BasicNameValuePair("package", "Sign=WXPay"));
                signParams.add(new BasicNameValuePair("partnerid", Constants.MCH_ID));
                signParams.add(new BasicNameValuePair("prepayid", prepayid));
                signParams.add(new BasicNameValuePair("timestamp", timeStamp));
                String sign = WeixinUtils.genSign(signParams);

                /*
                 * 支付接口业务处理 weiXinService.payBackSerivce(signParams, map);
                 * 修改订单状态和库存 修改代金券
                 */

                /*
                 * 返回手机端支付需要的全部参数
                 */
                outParams.put("retcode", "0");
                outParams.put("retmsg", "OK");
                outParams.put("appid", Constants.APP_ID);
                outParams.put("noncestr", noceStr);
                outParams.put("partnerid", Constants.MCH_ID);
                outParams.put("package", "Sign=WXPay");
                outParams.put("prepayid", prepayid);
                outParams.put("out_trade_no", out_trade_no);
                outParams.put("timestamp", timeStamp);
                outParams.put("sign", sign);
            } else {
                outParams.put("retcode", "-1");
                outParams.put("retmsg", "错误：获取不到Token");
            }
            Gson gson = new Gson();
            RemoteUtil.response(response, gson.toJson(outParams), 1, "返回成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void wxOAPay(int totalPrice, String body, String ip, String out_trade_no,
                        HttpServletRequest request, HttpServletResponse response,
                        List<OrderObject> list, int userID) {
        System.out.println("----创建微信预付定单-----");
        try {
            System.out.println("totalPrice--->" + totalPrice);
            System.out.println("product_name--->" + body);
            System.out.println("ip--->" + ip);
            /*
             * 调用统一支付接口
             */

            String notifyUrl = Path.weixin_pay_notifyurl_goods;
            String openid = request.getParameter("openID");

            Map<String, String> map = WeixinUtils.payUnifiedorder(WXPayType.OAPay, body,
                    totalPrice, ip, out_trade_no, notifyUrl, openid);
            TreeMap<String, String> outParams = new TreeMap<String, String>();
            if (null != map) {
                String app_id = map.get("appid");
                /*
                 * 获取预支付id
                 */
                String prepayid = map.get("prepay_id");
                /**
                 * 创建预支付sign签名
                 */
                String noceStr = RandomStringGenerator.getRandomStringByLength(32);
                String timeStamp = String.valueOf((System.currentTimeMillis() / 1000));

                List<NameValuePair> signParams = new LinkedList<NameValuePair>();
                signParams.add(new BasicNameValuePair("appId", app_id));
                signParams.add(new BasicNameValuePair("nonceStr", noceStr));
                signParams.add(new BasicNameValuePair("package", "prepay_id=" + prepayid));
                signParams.add(new BasicNameValuePair("signType", "MD5"));
                signParams.add(new BasicNameValuePair("timeStamp", timeStamp));
                String sign = WeixinUtils.genSign(signParams);

                /*
                 * 支付接口业务处理 weiXinService.payBackSerivce(signParams, map);
                 * 修改订单状态和库存 修改代金券
                 */

                /*
                 * 返回支付需要的全部参数
                 */
                outParams.put("retcode", "0");
                outParams.put("retmsg", "OK");
                outParams.put("appid", app_id);
                outParams.put("noncestr", noceStr);
                outParams.put("partnerid", Constants.OA_MCH_ID);
                outParams.put("package", "prepay_id=" + prepayid);
                outParams.put("prepayid", prepayid);
                outParams.put("out_trade_no", out_trade_no);
                outParams.put("timestamp", timeStamp);
                outParams.put("sign_type", "MD5");
                outParams.put("sign", sign);
            } else {
                outParams.put("retcode", "-1");
                outParams.put("retmsg", "错误：获取不到Token");
            }
            Gson gson = new Gson();
            RemoteUtil.response(response, gson.toJson(outParams), 1, "返回成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void aliPay(String totalFee, List<OrderObject> list, int userID, String orderID,
                       HttpServletResponse response, String out_trade_no) {
        TreeMap<String, String> outParams = new TreeMap<String, String>();
        // 设置支付回执
        String notifyURL = Path.ali_pay_notifyurl_goods;

        String orderName = "乡味汇商品";
        String orderDesc = "乡味汇";

        String sign = PayUtils.getSign(orderName, orderDesc, totalFee, notifyURL, out_trade_no);
        outParams.put("outTradeNo", out_trade_no);// tradeNo
        outParams.put("subject", "丛博科技商品");// 商品标题
        outParams.put("body", "商品");// 商品内容
        outParams.put("totleFee", totalFee + "");
        outParams.put("notifyURL", notifyURL);
        outParams.put("sign", sign);

        Gson gson = new Gson();
        RemoteUtil.response(response, gson.toJson(outParams), 1, "返回成功");
    }

    // 获取交易号
    public TradeNo generateTradeNo(String no, String orderIDs, int userID, int totalFee) {
        TradeNo tNo = new TradeNo();
        tNo.setOutTradeNo(no);
        tNo.setOrderIDs(orderIDs);
        tNo.setUserID(userID);
        tNo.setTotalFee(totalFee);
        tNo.setTradeNo("");
        return tNo;
    }

    ;

    // 删除购物车
    public void afterOrderCommit(int orderID, int userID, boolean isReduceSkuStock) {
        /*
         * 修改商品的库存，删除购物车，增加售出件数
         */
        List<OrderContent> contentList = orderManager.getOrderContent(orderID);
        for (OrderContent content : contentList) { // 修改商品的数量
            /*
             * 判断商品是否是活动商品
             */
            ActivityPrice ap = orderManager.getActivityPriceBySkuID(content.getSkuID());
            if (ap != null) {
                if (content.getActivityID() == 0) { // app的疯抢走这个逻辑
                    // 活动商品修改活动的销量
                    // orderManager.updateActivityGoodsSellout(ap.getActivityID(),content.getGoodsID(),
                    // content.getGoodsFormat(),content.getGoodsNumber());
                    // 修改库存
                    orderManager.reduceActivityNumber(ap.getActivityID(), ap.getSkuID(),
                            content.getGoodsNumber());
                }
            } else {
                if (isReduceSkuStock) {
                    int skuID = content.getSkuID();
                    int number = content.getGoodsNumber();
                    goodsManager.reduceSkuStock(skuID, number);
                    //goodsManager.updateGoodsStock(content.getGoodsID());
                }
            }
            // 删除购物车
            cartManager.delCartBySkuID(content.getSkuID(), userID);
        }
    }

    // 开启团购(修改商品的库存，删除购物车，增加售出件数)
    private int startGroup(int orderID, int userID) {
        //【1】获取订单内容
        List<OrderContent> contentList = orderManager.getOrderContent(orderID);
        for (OrderContent content : contentList) { // 修改商品的数量
            //要判断用户的下单是一个开团还是参团，就要看其中的group_id字段，如果等于0，就是开新团
            ThGroupBuying group = goodsManager.groupBuyingGetByRulesId(content.getActivityID());
            //首次开团
            if (content.getActivityName().equals("ThGroupBuyingRules") && group == null) {
                ThGroupBuyingRules rule = goodsManager.groupBuyingRuleGet(content.getActivityID());
                //判断是否可以开团
                int checkFlag = checkJoinGroupBuying(userID, rule, content.getGoodsNumber(), 0);
                if (checkFlag < 0) {
                    return checkFlag;
                }
                //扣库存(这里改成去掉sku中库存)
                boolean StockFlag = goodsManager.reduceSkuStock(content.getSkuID(),
                        content.getGoodsNumber());
                goodsManager.updateSkuSellOut(content.getSkuID(), content.getGoodsNumber());
                if (StockFlag) {
                    ThGroupBuying TGB = orderManager.groupAdd(content, rule, userID);
                    if (TGB != null) {
                        content.setGroupID(TGB.getId());
                        boolean updateFlag = orderManager.orderContentGroupIdAdd(content);
                        System.out.println("更新订单团购id" + TGB.getId() + "是否成功" + updateFlag);
                        return 1;
                    } else {
                        return -10;
                    }
                } else {
                    return -11;
                }
            } else {
                content.setGroupID(group.getId());
                orderManager.orderContentGroupIdAdd(content);
                boolean StockFlag = goodsManager.reduceSkuStock(content.getSkuID(),
                        content.getGoodsNumber());
                goodsManager.updateSkuSellOut(content.getSkuID(), content.getGoodsNumber());
                if (StockFlag) {
                    // 原来的商品要添加销量
                    // goodsManager.updateSellOut(content.getGoodsID(),
                    // content.getGoodsNumber());
                } else {
                    return -11;
                }
            }
            return 1; // 正常团购只有一个订单,所以直接在这里结束
        }
        return 1;
    }

    /**
     * @param content
     * @param userID
     * @return
     */
    private int startOrJoinGroup(OrderContent content, int userID) {
        int flag = 0;
        // 添加销售记录
        if (content.getActivityName().equals("ThGroupBuyingRules") && content.getActivityID() > 0) {
            flag = 1;
            //【1】增加销量
            orderManager.increaseStocks(content.getActivityID(), content.getGoodsNumber());

            //【2】查询团购信息和参团信息
            ThGroupBuying group = goodsManager.groupBuyingGet(content.getGroupID());
            ThGroupBuyingRules groupRules = goodsManager
                    .groupBuyingRuleGet(content.getActivityID());

            //【3】处理团购
            System.out.println("执行团购处理逻辑开始");
            if (group.getState() == 0) {
                // 开团 - 前面下单的时候已经占有一个开团位置，支付成功才解锁，真正开团
                group.setState(1);
                group.setStartedAt(new Timestamp(System.currentTimeMillis()));
                group.setEndAt(groupRules.getEndingAt());
                goodsManager.groupBuyingUpdate(group);
            } else {
                //判断是否支持购买
                int checkFlag = checkJoinGroupBuying(userID, groupRules, content.getGoodsNumber(),
                        content.getGroupID());
                // 支付成功，但是数量不够了，这个时候订单是成功的，但是团购是失败的
                if (checkFlag < 1) {
                    flag = -1;
                    System.out.println("加入团购状态：" + flag);
                } else {
                    // 参加团购人数加1
                    if (group.getState() == 1) {
                        int haveJoinPeople = group.getGroupJoinPeople();
                        haveJoinPeople = haveJoinPeople + 1;
                        group.setGroupJoinPeople(haveJoinPeople);
                        System.out.println("执行团购处理逻辑开始：+1");
                        orderManager.groupUpdate(group);
                    } else {
                        flag = -3;
                        System.out.println("加入团购状态：" + flag);
                    }
                }
            }
        } else {
            return -100;
        }
        return 0;
    }

    private void sendSucessMsgForGroupBuying(int groupId) {
        List<?> orderList = goodsManager.groupByingHistoryGet(groupId);
        for (int i = 0; i < orderList.size(); i++) {
            Object[] obj = (Object[]) orderList.get(i);
            int userId = Integer.parseInt(obj[0].toString());
            String fee = obj[3].toString();
            BigDecimal bFee = new BigDecimal(fee);
            String title = obj[4].toString();
            ThClientPlatforms thClientPlatforms = accountManager.getClientPlatformByUserId(userId);
            if (thClientPlatforms != null) {
                logger.info("团购成功，给所有参团人员发送模板信息，用户openid：" + thClientPlatforms.getOpenId()
                        + ",用户购买商品：" + title + ",用户付款金额：" + bFee);
                TemplateMessageUtil.sendGroupBuyingSuccessMessage(thClientPlatforms.getOpenId(),
                        title, bFee);
            }
        }
    }

    // 添加商店用户
    public void addShopClient(int shopID, int userID, String phone, String name) {
        // 添加用户为商店用户
        ShopClient shopClient = new ShopClient();
        shopClient.setShopID(shopID);
        shopClient.setUserID(userID);
        shopClient.setPhone(phone);
        shopClient.setUserName(name);
        orderManager.addShopClienit(shopClient);
    }

    // 订单取消
    public void cancelOrder(HttpServletRequest request, HttpServletResponse response) {
        String orderID = request.getParameter("orderID");
        int userID = Integer.parseInt(request.getParameter("userID"));
        String userToken = request.getParameter("userToken");
        valiTag = accountManager.validate(userID, userToken);
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        List<OrderContent> list = orderManager.getOrderContent(Integer.parseInt(orderID));

        // if (order.getStation() != 1) {
        // RemoteUtil.response(response, null, -1, "操作失败");
        // return;
        // }

        opTag = orderManager.cancelOrder(Integer.parseInt(orderID));
        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
            /*
             * 取消订单还原订单数量
             */
            for (OrderContent content : list) {
                int number = content.getGoodsNumber();
                if (content.getActivityID() > 0) {
                    if (content.getActivityName().equals("ThGroupBuyingRules")) {
                        // 团购活动
                        orderManager.rollbackStocks(content.getActivityID(),
                                content.getGoodsNumber());
                        //之前减去的库存恢复回来
                        goodsManager.reduceSkuStock(content.getSkuID(), -number);
                    } else if (content.getActivityName().equals("ThPanicBuyingSku")) {
                        // 疯抢活动
                        orderManager.reduceActivityNumber(content.getActivityID(),
                                content.getSkuID(), -number);
                    }
                } else {
                    goodsManager.reduceSkuStock(content.getSkuID(), -number);
                    goodsManager.updateGoodsStock(content.getGoodsID());
                }
            }

        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    // 订单取消
    public void delOrder(HttpServletRequest request, HttpServletResponse response) {
        String orderID = request.getParameter("orderID");
        int userID = Integer.parseInt(request.getParameter("userID"));
        String userToken = request.getParameter("userToken");
        valiTag = accountManager.validate(userID, userToken);
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }
        opTag = orderManager.delOrder(Integer.parseInt(orderID));
        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    // 退款申请
    // public void refund(HttpServletRequest request, HttpServletResponse
    // response) {
    // Refund refund = (Refund) RemoteUtil.request(request, new Refund());
    // String userToken = request.getParameter("userToken");
    // valiTag = accountManager.validate(refund.getUserID(), userToken);
    // if (!valiTag) {
    // RemoteUtil.response(response, null, -100, "身份异常");
    // return;
    // }
    //
    // refund.setStation(0);// 申请中
    // Order order = orderManager.getOrder(refund.getOrderID());
    // refund.setShopID(order.getShopID());
    //
    // ClientAccount account =
    // accountManager.getAccount(null,refund.getUserID());
    // if (account == null) {
    // RemoteUtil.response(response, null, -1, "操作失败");
    // return;
    // }
    //
    // Refund oldRefund = orderManager.getRefund(refund.getOrderID(),
    // refund.getGoodsID(), refund.getGoodsFormat());
    // if(oldRefund!=null){
    // RemoteUtil.response(response, null, -1, "操作失败");
    // return;
    // }
    //
    // refund.setPhone(account.getPhone());
    // opTag = orderManager.addRefund(refund);
    // if (opTag) {
    // RemoteUtil.response(response, null, 1, "操作成功");
    // // 修改付款订单的时间
    //// orderManager.updateOrderTime(Integer.parseInt(orderID),
    // 2,System.currentTimeMillis());// 修改订单付款的时间
    //// // 操作成功，修改订单状态为售后
    //// orderManager.updateOrderStation(refund.getOrderID(), 7);
    // } else {
    // RemoteUtil.response(response, null, -1, "操作失败");
    // }
    // }

    // 退款列表
    public void refundList(HttpServletRequest request, HttpServletResponse response) {
        String userID = request.getParameter("userID");
        String cPage = request.getParameter("page");

        PageUtil page = new PageUtil(Integer.parseInt(cPage));
        int refundStation = 7;// 订单退款

        List<Order> orderList = orderManager.orderList(Integer.parseInt(userID), refundStation,
                page);
        // List<JsonOrder> returnList = OrderParse.orderListParse(orderList,
        // orderManager);
        List<JsonOrder> returnList = OrderParse.orderListParse(orderList, orderManager,
                goodsManager);

        for (Order order : orderList) {
            Refund refund = orderManager.getRefund(order.getOrderID());
            order.setStation(refund.getStation());
            order.setRefundFee(refund.getRefundFee() + "");
        }

        RemoteUtil.response(response, returnList, 1, "返回成功");
    }

    // 获取订单列表
    public void orderList(HttpServletRequest request, HttpServletResponse response) {
        String userID = request.getParameter("userID");
        String station = request.getParameter("station");
        String cPage = request.getParameter("page");
        PageUtil page = new PageUtil(Integer.parseInt(cPage));

        List<Order> orderList = orderManager.orderList(Integer.parseInt(userID),
                Integer.parseInt(station), page);
        List<JsonOrder> returnList = OrderParse.orderListParse(orderList, orderManager,
                goodsManager);

        //【3】对应的商品的剩余额购买数量
        for (JsonOrder order : returnList) {
            for (OrderContent content : order.getOrderContent()) {
                if (("ThGroupBuyingRules").equals(content.getActivityName())) {
                    //查询团购基本信息
                    ThGroupBuyingRules rule = goodsManager.groupBuyingRuleGet(content
                            .getActivityID());
                    int buyingAmount = directSupplyGoodsManager.getUserGroupBuyingAmount(
                            content.getActivityID(), Integer.parseInt(userID));
                    int leftAmount = rule.getGoodsLimitBuy() - buyingAmount;
                    content.setGoodsLimitBuy(leftAmount);
                }
            }
        }

        RemoteUtil.response(response, returnList, 1, "返回成功");
    }

    public void diretorPrivilegeOrderList(HttpServletRequest request, HttpServletResponse response) {
        String userID = request.getParameter("userID");
        String cPage = request.getParameter("page");
        PageUtil page = new PageUtil(Integer.parseInt(cPage));

        List<Order> orderList = orderManager.diretorPrivilegeOrderList(Integer.parseInt(userID));
        List<JsonOrder> returnList = OrderParse.orderListParse(orderList, orderManager,
                goodsManager);

        RemoteUtil.response(response, returnList, 1, "返回成功");
    }

    // 获取订单详情
    public void orderContent(HttpServletRequest request, HttpServletResponse response) {
        String userID = request.getParameter("userID");

        String userToken = request.getParameter("userToken");
        String orderID = request.getParameter("orderID");
        valiTag = accountManager.validate(Integer.parseInt(userID), userToken);
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        // 订单
        Order order = orderManager.getOrder(Integer.parseInt(orderID));
        // 商店
        Shop shop = goodsManager.shopDetail(order.getShopID());
        // 获取商品详情默认回复语句
        AutoReply reply = goodsManager.getAutoReply(shop.getShopID());

        if (order.getStation() == 5) {// 订单处于评价者，需要判断商品是否已经进行了评价
        }

        // 订单内容
        List<OrderContent> contentList = orderManager.getOrderContent(Integer.parseInt(orderID));// 订单列表

        for (OrderContent content : contentList) {
            // 商家ID
            content.setBussinessID(shop.getBussinessID());
            content.setShopName(shop.getShopName());
            content.setShopID(shop.getShopID());
            // 商家回复语
            if (reply == null) {
                content.setAutoReplyMessage("欢迎登陆本店");
            } else {
                // 判断当前时间是否在工作时间段内
                String st = reply.getStartTime();
                String et = reply.getEndTime();

                boolean tag = TimeUtil.inTime(st, et);
                if (tag) {// 当前时间在工作时间之内
                    content.setAutoReplyMessage(reply.getWorkMessage());
                } else {
                    content.setAutoReplyMessage(reply.getOffMessage());
                }
            }
            // 店铺logo
            content.setShopLogo(Path.nginxServerBusinessDir + Path.SHOP + File.separator
                    + Path.LOGO + File.separator + shop.getShopLogo());

            if (("ThGroupBuyingRules").equals(content.getActivityName())) {
                //查询团购基本信息
                ThGroupBuyingRules rule = goodsManager.groupBuyingRuleGet(content.getActivityID());
                int buyingAmount = directSupplyGoodsManager.getUserGroupBuyingAmount(
                        content.getActivityID(), Integer.parseInt(userID));
                int leftAmount = rule.getGoodsLimitBuy() - buyingAmount;
                content.setGoodsLimitBuy(leftAmount);
            }

        }

        // 订单物流
        OrderLogistic logistic = orderManager.getOrderLogistic(Integer.parseInt(orderID));
        // 商家ID
        String serverID = "1000000";
        // 商家电话
        String serverPhone = "4008018015";

        JsonOrderContent content = new JsonOrderContent();
        content.setLogistic(logistic);// 物流
        content.setOrderContent(contentList);// 商品列表

        content.setState(order.getStation()); // 订单状态
        content.setServerID(serverID);
        content.setServerPhone(serverPhone);
        content.setOpTime(order.getOpTime());
        content.setTransactionNumber(order.getTransactionNumber());
        content.setOrderFee(order.getFee());

        // content.setBussinessID(shop.getBussinessID());
        RemoteUtil.response(response, content, 1, "返回成功");
    }

    // 支付宝通知
    @SuppressWarnings("unchecked")
    public void aliNotify(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("-----------aliNotify-------------");

        String outTradeNo = request.getParameter("out_trade_no");
        TradeNo tradeNo = orderManager.getTradeNo(outTradeNo);
        String sellId = request.getParameter("seller_id");
        String inTradeNo = request.getParameter("trade_no");
        String tradeStatus = request.getParameter("trade_status");
        int totalFee = (int) (Float.parseFloat(request.getParameter("total_fee")) * 100);

        // 生成验签需要的map并做验签
        Map<String, String> paramsMap = new HashMap<String, String>();
        Iterator<?> entries = request.getParameterMap().entrySet().iterator();
        while (entries.hasNext()) {
            Entry<String, String[]> entry = (Entry<String, String[]>) entries.next();
            String name = (String) entry.getKey();
            String[] valueObj = entry.getValue();
            String value = valueObj[0];
            if (!name.equals("method")) {
                paramsMap.put(name, value);
            }
        }

        boolean signVerified = false;
        try {
            // TODO [signVerified = AlipaySignature.rsaCheckV1(paramsMap, PayUtils.ALIPAY_PUBLIC_KEY, "utf-8")]
            signVerified = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        boolean paySuccess = true;

        // 验签
        if (!signVerified) {
            paySuccess = false;
        }

        // 验证订单号
        if (!tradeNo.getOutTradeNo().equals(outTradeNo)) {
            paySuccess = false;
        }

        // 验证金额
        if (!((totalFee > tradeNo.getTotalFee() - 10) && (totalFee < tradeNo.getTotalFee() + 10))) {
            paySuccess = false;
        }

        // 验证商户id
        if (!sellId.equals(PayUtils.PARTNER)) {
            paySuccess = false;
        }

        // 验证支付结果
        if (!tradeStatus.equals("TRADE_SUCCESS")) {
            paySuccess = false;
        }

        // 还有一个验证app_id，但是支付宝现在没返回这个字段，腊鸡！该应用逻辑倒是不需要验证也能保证安全，所以暂时不验证。

        if (paySuccess) {
            tradeNo.setTradeNo(inTradeNo);
            orderManager.tradeNoUpdate(tradeNo);

            String orderIds = tradeNo.getOrderIDs();
            String orderIDArr[] = orderIds.split(";");
            for (String orderID : orderIDArr) {
                // TODO 这个是什么意思？
                Order order = orderManager.getOrder(Integer.parseInt(orderID));
                if (order == null || order.getStation() != 1) {// 不是未支付的状态
                    continue;
                }

                // 修改礼品金额
                float giftCardMoney = order.getGiftcardFee();
                int userID = order.getUserID();
                orderManager.deleteCouponCount(userID, giftCardMoney);

                // 添加销量
                List<OrderContent> contentList = orderManager.getOrderContent(Integer
                        .parseInt(orderID));
                for (OrderContent content : contentList) {
                    addSellOut(order.getShopID(), content.getGoodsID(), content.getGoodsNumber(),
                            content.getFee(), content.getGoodsFormat());
                    ActivityPrice ap = orderManager.getActivityPriceBySkuID(content.getSkuID());
                    if (ap != null) {
                        orderManager.updateActivityGoodsSellout(ap.getActivityID(),
                                content.getGoodsID(), content.getGoodsFormat(),
                                content.getGoodsNumber());
                    } else {
                        goodsManager.updateSellOut(content.getGoodsID(), content.getGoodsNumber());// 修改销量
                    }
                }

                int station = 2;// station= 2 表示待发货
                // 修改订单的状态和交易的类型和交易的时间
                orderManager.updateOrderStationAndTransaction(Integer.parseInt(orderID), station,
                        1, tradeNo.getTradeNo());
                // 修改付款订单的时间
                orderManager.updateOrderTime(Integer.parseInt(orderID), 2,
                        System.currentTimeMillis());// 修改订单付款的时间
                // 发送消息
                payNews(userID, Integer.parseInt(orderID));

                // 加入分销信息
                addSURecord(Integer.parseInt(orderID), userID);
            }
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        try {
            if (paySuccess) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("fail");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 微信通知
    @SuppressWarnings("unchecked")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) {
        InputStream inputStream = null;
        Map<String, String> map = null;
        try {
            // 解析结果存储在TreeMap
            map = new TreeMap<String, String>();
            inputStream = request.getInputStream();
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            for (Element e : elementList) {
                if (e.getName() != null && e.getText() != null) {
                    map.put(e.getName(), "" + e.getText());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (inputStream != null) {
                    inputStream.close();
                    inputStream = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        boolean paySuccess = true;

        logger.info("微信异步通知，返回结果：" + map);
        try {
            if (!"SUCCESS".equals(map.get("return_code"))) {
                paySuccess = false;
            }

            // 签名验证
            List<NameValuePair> signParams = new LinkedList<NameValuePair>();
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = map.get(key);
                if (!key.equals("sign") && value != null) {
                    signParams.add(new BasicNameValuePair(key, value));
                }
            }

            String computationalSign = WeixinUtils.genSign(signParams);
            String originalSign = map.get("sign");
            if (!computationalSign.equals(originalSign)) {
                paySuccess = false;
            }

            // 结果验证
            if (!map.get("result_code").equals("SUCCESS")) {
                paySuccess = false;
            }

            // appid验证
            String appId = (map.get("trade_type").equals("APP") ? Constants.APP_ID
                    : Constants.OA_APP_ID);
            if (!map.get("appid").equals(appId)) {
                paySuccess = false;
            }

            // 商户id验证
            String mchId = (map.get("trade_type").equals("APP") ? Constants.MCH_ID
                    : Constants.OA_MCH_ID);
            if (!map.get("mch_id").equals(mchId)) {
                paySuccess = false;
            }

            // 商户系统订单号验证
            String tradeNo = map.get("out_trade_no");
            TradeNo trade = orderManager.getTradeNo(tradeNo);
            if (trade == null) {
                paySuccess = false;
            }

            // 订单金额验证
            int totalFee = Integer.parseInt(map.get("total_fee"));
            if (!((totalFee > trade.getTotalFee() - 10) && (totalFee < trade.getTotalFee() + 10))) {
                paySuccess = false;
            }

            //这里可能会出现异常情况

            if (paySuccess) {
                String transactionNo = map.get("transaction_id");
                trade.setTradeNo(transactionNo);
                orderManager.tradeNoUpdate(trade);

                String sOrderID = trade.getOrderIDs();
                String orderIDArr[] = sOrderID.split(";");

                //如果用户使用0.01元董事特权，则该用户的董事特权总次数减1
                ClientAccount account = accountManager.getAccount(null, trade.getUserID());
                int useageCount = account.getPrivilegeUsageCount();
                if (useageCount > 0) {
                    account.setPrivilegeUsageCount(useageCount - 1);
                    accountManager.updateClientAccount(account);
                }

                for (String orderID : orderIDArr) {

                    int station = 2; // station= 2 表示待发货
                    Order order = orderManager.getOrder(Integer.parseInt(orderID));

                    if (order == null) {
                        continue;
                    }

                    if (order.getStation() != 1) {
                        //正常订单状态应该为1，有部分订单可能出现订单状态被修改的情况，这里做下记录
                        logger.info("状态异常订单【漏单】，订单编号：" + order.getOrderID());
                    }

                    // 修改订单的状态和交易的类型和交易的时间
                    int feeType = (map.get("trade_type").equals("APP") ? 2 : 6);
                    orderManager.updateOrderStationAndTransaction(Integer.parseInt(orderID),
                            station, feeType, transactionNo);

                    // 修改付款订单的时间
                    orderManager.updateOrderTime(Integer.parseInt(orderID), 2,
                            System.currentTimeMillis());// 修改订单付款的时间
                    payNews(order.getUserID(), Integer.parseInt(orderID));

                    // 添加销量
                    updateSellout(order, order.getUserID());

                    // 修改礼品金额
                    float giftCardMoney = order.getGiftcardFee();
                    int userID = order.getUserID();
                    orderManager.deleteCouponCount(userID, giftCardMoney);

                    // 加入分销信息
                    addSURecord(Integer.parseInt(orderID), userID);
                }
            }
        } catch (Exception e1) {
            logger.info("微信异步通知，更新订单状态异常：" + e1 + ",异常的订单：" + map);
        }

        /*
         * 操作成功，返回微信SUCCESS
         */
        response.resetBuffer();
        response.setContentType("text/xml; charset=UTF-8");
        String returnXml = null;
        if (paySuccess) {
            returnXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        } else {
            returnXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }

        try {
            PrintWriter writer = response.getWriter();
            writer.print(returnXml);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 添加销量
    public void addSellOut(int shopID, int goodsID, int number, double fee, String goodsFormat) {
        SelloutRecord record = new SelloutRecord();
        record.setShopID(shopID);
        record.setGoodsID(goodsID);
        record.setNumber(number);
        record.setFee((float) fee);
        record.setGoodsFormat(goodsFormat);

        orderManager.addSellout(record);
    }

    // 交易消息
    public void payNews(int userID, int orderID) {
        int typeA = 4;
        String typeB = "";
        String title = "交易提醒";
        String content = "您的订单已支付完成，商家会及时给您发货，感谢您的惠顾！";
        String picture = null;
        String param = "orderID:" + orderID;
        NewsCenter.news(userID, typeA, typeB, title, content, picture, param, newsManager, true);
    }

    // 添加评论
    public void deliveryConfirm(HttpServletRequest request, HttpServletResponse response) {

        String userID = request.getParameter("userID");
        String userToken = request.getParameter("userToken");
        String orderID = request.getParameter("orderID");
        valiTag = accountManager.validate(Integer.parseInt(userID), userToken);
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        int station = 5;// 确认收获，待评价
        opTag = orderManager.updateOrderStation(Integer.parseInt(orderID), station);
        // 修改付款订单的时间
        orderManager.updateOrderTime(Integer.parseInt(orderID), 5, System.currentTimeMillis());// 修改订单付款的时间
        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    // 修改销量
    //	public void updateSellOut(int orderID) {
    //		List<OrderContent> contentList = orderManager.getOrderContent(orderID);
    //
    //		for (OrderContent content : contentList) {
    //			int goodsID = content.getGoodsID();
    //			int number = content.getGoodsNumber();
    //			// 修改一下商品销量
    //			goodsManager.updateSellOut(goodsID, number);
    //
    //		}
    //	}

    // 查看快递
    public void express(HttpServletRequest request, HttpServletResponse response) {
        String orderID = request.getParameter("orderID");
        OrderLogistic logi = orderManager.getOrderLogistic(Integer.parseInt(orderID));

        String key = logi.getExpressKey();
        String number = logi.getExpressNumber();

        String returnJson = HttpClientUtil.getHttp(number, key);
        RemoteUtil.response(response, returnJson, 1, "返回成功");
    }

    // 添加评论
    public void addComment(HttpServletRequest request, HttpServletResponse response) {

        Comment comment = (Comment) RemoteUtil.request(request, new Comment());

        String commentContent = comment.getContent();
        // 判断内容里面是否含有敏感词
        if (commentContent == null || commentContent.equals("")) {
            comment.setContent("好评");
        }
        boolean sensetiveTag = SensetiveWord.hasSensetiveWord(commentContent);
        if (!sensetiveTag) {// 含有敏感词汇
            RemoteUtil.response(response, null, -2, "您的评论含有敏感词汇");
            return;
        }

        opTag = orderManager.addComment(comment);
        // 如果该订单下面所有的商品都已经评论了，修改订单的状态
        List<OrderContent> contentList = orderManager.getOrderContent(comment.getOrderID());// 获取所有的订单详情的列表
        // 判断是否所有订单都有评论了
        boolean tag = true;
        for (OrderContent content : contentList) {
            boolean existTag = orderManager.isComment(comment.getOrderID(), content.getGoodsID(),
                    content.getGoodsFormat(), comment.getUserID());
            if (!existTag) {
                tag = false;
                break;
            }
        }
        if (tag) {// 表示所有的商品都已经评论了
            // 修改
            int station = 6;
            orderManager.updateOrderStation(comment.getOrderID(), station);
        }
        if (opTag) {
            RemoteUtil.response(response, null, 1, "操作成功");
            if (tag) {
                // 修改付款订单的时间
                orderManager.updateOrderTime(comment.getOrderID(), 6, System.currentTimeMillis());// 修改订单评价的时间
            }
        } else {
            RemoteUtil.response(response, null, -1, "操作失败");
        }
    }

    /**
     * 粉丝下单，保存分润记录，给推荐人发送相关通知
     *
     * @param orderId
     * @param userId
     */
    public void addSURecord(int orderId, int userId) {
        // 加入分销信息
        //【1】获取推广人id及分润比例
        Object[] subUnderwriterObj = subUnderwritingManager.subUnderwriterInfo(userId);

        //判断是否存在当前订单的分销订单记录(已经进行分销的就不再分销)
        boolean subUnderwritingOrderExistence = subUnderwritingManager
                .subUnderwritingOrderExistence(orderId);

        //获取订单的普通商品总价 
        BigDecimal totalFee = orderManager.orderSubUnderwritingTotalFee(orderId);

        //获取单个订单的分润金额
        BigDecimal maxProfitShare = subUnderwritingManager.getOrderProfitShare(orderId);

        if (subUnderwriterObj != null && !subUnderwritingOrderExistence
                && totalFee.compareTo(BigDecimal.valueOf(0)) == 1
                && maxProfitShare.compareTo(BigDecimal.valueOf(0)) == 1) {

            //直接推广人
            int underwriterId1 = Integer.parseInt(subUnderwriterObj[0].toString());

            //判断下单用户是否为懂事特权用户
            boolean flag = true;
            ClientAccount clientAccount = accountManager.getAccount(null, userId);

            if (clientAccount.getPrivilegeExpiration() == null
                    || clientAccount.getPrivilegeExpiration().before(new Date())) {
                flag = false;
            }

            //根据用户是否为董事特权用户，设置商品订单1,2级分润比例
            double level1Profit;
            double level2Profit;
            if (flag) {
                //用户为董事用户
                level1Profit = 0.03;
                level2Profit = 0.015;
            } else {
                //用户为非董事用户
                level1Profit = 0.45;
                level2Profit = 0.225;
            }

            //给直接代理人发放收益
            grantProfit(orderId, underwriterId1, level1Profit, totalFee, maxProfitShare);

            //用户有间接代理人，则给间接代理人发放收益
            Object[] subUnderwriterObj1 = subUnderwritingManager.subUnderwriterInfo(new Integer(
                    underwriterId1));
            if (subUnderwriterObj1 != null && subUnderwriterObj1[0] != null) {
                grantProfit(orderId, Integer.parseInt(subUnderwriterObj1[0].toString()),
                        level2Profit, totalFee, maxProfitShare);
            }

        }
    }

    /**
     * 生成推广人分润订单，并推送消息
     *
     * @param orderId        订单编号
     * @param underwriterId  推广人ID
     * @param ratio          分润比例
     * @param totalFee       订单商品总价
     * @param maxProfitShare 订单最大分润金额（sku单个商品最大分润金额x订单商品数量）
     */
    private void grantProfit(int orderId, int underwriterId, double ratio, BigDecimal totalFee,
                             BigDecimal maxProfitShare) {

        BigDecimal income = maxProfitShare.multiply(new BigDecimal(ratio)).setScale(2,
                BigDecimal.ROUND_HALF_UP);

        //保存推广人发放分润订单
        ThSubUnderwritingOrders subUnderwritingOrder = new ThSubUnderwritingOrders();
        subUnderwritingOrder.setSubUnderwriterId(underwriterId);
        subUnderwritingOrder.setRatio(new BigDecimal(ratio));
        subUnderwritingOrder.setState(0);
        subUnderwritingOrder.setMaxProfitShare(income.multiply(new BigDecimal(100)).intValue());
        subUnderwritingOrder.setTotalFee(totalFee);
        subUnderwritingOrder.setOrderId(orderId);
        subUnderwritingManager.subUnderwritingOrderAdd(subUnderwritingOrder);

        // 对粉丝下单进行推送
        ThClientPlatforms clientPlatform = accountManager
                .getClientPlatformByUserId(subUnderwritingOrder.getSubUnderwriterId());
        if (clientPlatform != null) {
            List<OrderContent> orderContents = orderManager.getOrderContent(orderId);
            String goodsTitle = "";
            for (int i = 0; i < orderContents.size(); i++) {
                OrderContent content = orderContents.get(i);
                goodsTitle = goodsTitle + content.getGoodsTitle() + " ";
            }
            TemplateMessageUtil.sendFansOrderCommitMessage(clientPlatform.getOpenId(), goodsTitle,
                    income);
        }
    }

    private void updateSellout(Order order, int userId) {
        // 添加销量
        List<OrderContent> contentList = orderManager.getOrderContent(order.getOrderID());
        for (OrderContent content : contentList) {
            addSellOut(order.getShopID(), content.getGoodsID(), content.getGoodsNumber(),
                    content.getFee(), content.getGoodsFormat());

            //goodsManager.reduceSkuStock(content.getSkuID(), content.getGoodsNumber());

            content.setActivitySuccess(1);
            orderManager.orderContentUpdate(content);

            int flag = startOrJoinGroup(content, userId);

            /*
             * 判断商品是否是活动商品
             */
            ActivityPrice ap = null;
            if (content.getSkuID() != 0)
                ap = orderManager.getActivityPriceBySkuID(content.getSkuID());
            else
                ap = orderManager.getActivityPrice(content.getGoodsID(), content.getGoodsFormat());
            if (flag == -100) {
                if (ap == null) {// 不是活动商品
                    goodsManager.updateSkuSellOut(content.getSkuID(), content.getGoodsNumber());
                } else {
                    //					orderManager.updateActivityGoodsSellout(ap.getActivityID(), content.getGoodsID(),
                    //							content.getGoodsFormat(), content.getGoodsNumber());
                    orderManager.updateActivityGoodsSellout(ap.getActivityID(), content.getSkuID(),
                            content.getGoodsNumber());
                }
            }
        }
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = "192.168.1.1"; // 实在出问题时没办法
        }

        int commaOffset = ip.indexOf(',');
        if (commaOffset < 0) {
            return ip;
        } else {
            return ip.substring(0, commaOffset);
        }
    }

    /**
     * @param directSupplyGoodsManager the directSupplyGoodsManager to set
     */
    public void setDirectSupplyGoodsManager(DirectSupplyGoodsManager directSupplyGoodsManager) {
        this.directSupplyGoodsManager = directSupplyGoodsManager;
    }
}

class OrderObject {
    private int orderID;        // 订单ID
    private String message;        // 买家留言
    private String invoice;        // 发票
    private String congratulations; // 贺词
    private String deliveryTime;   // 订单时间

    private int couponID;       // 代金券ID
    private float couponFee;      // 代金券金额
    private float giftcardMoney;  // 礼品卡金额
    private float money;          // 现金
    private int station;        // 订单状态
    private int transactionType; // 交易类型

    public String getDeliveryTime() {
        return deliveryTime;
    }

    public void setDeliveryTime(String deliveryTime) {
        this.deliveryTime = deliveryTime;
    }

    public String getCongratulations() {
        return congratulations;
    }

    public void setCongratulations(String congratulations) {
        this.congratulations = congratulations;
    }

    public String getInvoice() {
        return invoice;
    }

    public void setInvoice(String invoice) {
        this.invoice = invoice;
    }

    public float getCouponFee() {
        return couponFee;
    }

    public void setCouponFee(float couponFee) {
        this.couponFee = couponFee;
    }

    public int getCouponID() {
        return couponID;
    }

    public void setCouponID(int couponID) {
        this.couponID = couponID;
    }

    public float getGiftcardMoney() {
        return giftcardMoney;
    }

    public void setGiftcardMoney(float giftcardMoney) {
        this.giftcardMoney = giftcardMoney;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }

    public int getOrderID() {
        return orderID;
    }

    public void setOrderID(int orderID) {
        this.orderID = orderID;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getStation() {
        return station;
    }

    public void setStation(int station) {
        this.station = station;
    }

    public int getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(int transactionType) {
        this.transactionType = transactionType;
    }

}
